package com.jsh.erp.service.depotHead;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Sets;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.datasource.vo.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.WorkflowConfig.WorkflowConfigService;
import com.jsh.erp.service.account.AccountService;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.accountItem.AccountItemService;
import com.jsh.erp.service.attachment.AttachmentService;
import com.jsh.erp.service.depot.DepotService;
import com.jsh.erp.service.depotItem.DepotItemService;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.material.MaterialService;
import com.jsh.erp.service.materialExtend.MaterialExtendService;
import com.jsh.erp.service.orgaUserRel.OrgaUserRelService;
import com.jsh.erp.service.person.PersonService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.sequence.SequenceService;
import com.jsh.erp.service.serialNumber.SerialNumberService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.support.collections.DefaultRedisList;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.jsh.erp.utils.Tools.getCenternTime;
import static com.jsh.erp.utils.Tools.getNow3;

@Service
public class DepotHeadService {
    private Logger logger = LoggerFactory.getLogger(DepotHeadService.class);

    @Resource
    private DepotHeadMapper depotHeadMapper;
    @Resource
    private DepotHeadMapperEx depotHeadMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private DepotService depotService;
    @Resource
    DepotItemService depotItemService;
    @Resource
    private SupplierService supplierService;
    @Resource
    private SerialNumberService serialNumberService;
    @Resource
    private OrgaUserRelService orgaUserRelService;
    @Resource
    private PersonService personService;
    @Resource
    private AccountService accountService;
    @Resource
    private AccountItemService accountItemService;
    @Resource
    private DepotItemMapperEx depotItemMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private RedisService redisService;
    @Resource
    private UserBusinessService userBusinessService;
    @Resource
    private WorkflowConfigService workflowConfigService;
    @Resource
    private WorkflowProcessDetailMapperEx workflowProcessDetailMapperEx;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private MaterialService materialService;
    @Resource
    private MaterialExtendService materialExtendService;
    @Resource
    private AttachmentService attachmentService;
    @Resource
    private AttachmentMapperEx attachmentMapperEx;
    @Resource
    private MsgMapper msgMapper;
    @Resource
    private RetailRecordMapperEx retailRecordMapperEx;
    @Resource
    private RetailRecordMapper retailRecordMapper;
    @Resource
    private DepotItemMapper depotItemMapper;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private FunctionService functionService;
    @Resource
    private WorkflowApproveDetailMapperEx workflowApproveDetailMapperEx;
    @Resource
    private WorkflowApproveDetailMapper workflowApproveDetailMapper;
    @Resource
    private AccountHeadMapperEx accountHeadMapperEx;
    @Resource
    private AccountHeadMapper accountHeadMapper;
    @Resource
    private AccountItemMapperEx accountItemMapperEx;
    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private DepotMapperEx depotMapperEx;
    @Resource
    private SynchronizationTaskMapperEx synchronizationTaskMapperEx;


    public DepotHead getDepotHeadById(String id) throws Exception {
        DepotHead result = null;
        try {
            result = depotHeadMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public DepotHead getDepotHeadByIdNotTenant(String id) throws Exception {
        DepotHead result = null;
        try {
            result = synchronizationTaskMapperEx.selectDepotHeadById(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHead> getDepotHead() throws Exception {
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = null;
        try {
            list = depotHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotHeadVo4List> select(String type, String subType, String roleType, String status, String purchaseStatus, String number, String linkNumber,
                                         String beginTime, String endTime, String materialParam, String organId, String creator, String depotId, String accountId,
                                         String remark, String custom3, int offset, int rows, String payStatus, String freightStatus, String quotationStatus,
                                         String custom4,String color,String alwaysSelect,String itemType,String creditStatus,String depotStatus,String column,
                                         String order) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] depotArray = getDepotArray(subTypeList);
            String[] depotArrays = getDepotArrayByDepotStatus(depotStatus);
            String[] creatorArray = getCreatorArray(roleType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            String[] quotationStatusArray = StringUtil.isNotEmpty(quotationStatus) ? quotationStatus.split(",") : null;
            String[] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
//            Map<String, String> personMap = personService.getPersonMap();
//            Map<String, String> departMap = personService.getPersonDepartMap();
            Map<String, String> accountMap = accountService.getAccountMap();
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            if (StringUtil.isEmpty(column)){
                column="operTime";
            }
            list = depotHeadMapperEx.selectByConditionDepotHead(typeList, subTypeList, creatorArray, statusArray, purchaseStatusArray, number, linkNumber, beginTime, endTime,
                    materialParam, organId, creator, depotId, depotArray, accountId, remark, custom3, offset, rows, payStatus, freightStatus,quotationStatusArray,custom4
            ,color,alwaysSelect,itemType,creditStatus,depotStatus,depotArrays,column,order);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (accountMap != null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
                        String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
                        dh.setAccountName(accountStr);
                    }
                    if (dh.getAccountIdList() != null) {
                        String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountIdList(accountidlistStr);
                    }
                    if (dh.getAccountMoneyList() != null) {
                        String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountMoneyList(accountmoneylistStr);
                    }
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if (dh.getDeposit() == null) {
                        dh.setDeposit(BigDecimal.ZERO);
                    }
//                    dh.setFinishDeposit(depotHeadMapperEx.getFinishDepositByNumber(dh.getNumber()));
                    if (StringUtil.isNotEmpty(dh.getSalesMan())) {
                        User user = userService.getUser(dh.getSalesMan());
                        if (null !=user){
                            dh.setSalesManStr(user.getLoginName());
                            dh.setSalesUserName(user.getUsername());
                        }
//                        dh.setSalesManStr(personService.getPersonByMapAndIds(personMap, dh.getSalesMan()));
//                        dh.setDepartment(personService.getPersonByMapAndIds(departMap, dh.getSalesMan()));
                    }
                    if (StringUtil.isNotEmpty(dh.getDepotId())) {
                        dh.setDepotName(depotService.getAnotherDepotById(dh.getDepotId()));
                    }
                    if (StringUtil.isNotEmpty(dh.getCheckDepotId())) {
                        dh.setCheckDepotName(depotService.getDepotById(dh.getCheckDepotId()));
                    }
                    if (StringUtil.isNotEmpty(dh.getAnotherDepotId())) {
                        dh.setAnotherDepotName(depotService.getAnotherDepotById(dh.getAnotherDepotId()));
                    }
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getArrivalTime() != null) {
                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
                    }
                    if (StringUtils.isNotEmpty(dh.getLinkNumber()) && "下达采购".equals(dh.getSubType())){
                        dh.setClientName(depotHeadMapperEx.getClientNameByNumber(dh.getLinkNumber()));
                    }
                    if ("厂家直发".equals(dh.getSubType())){
                        Map<String, Object> depositMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "3");
                        //订金
                        dh.setStraightDeposit((BigDecimal) depositMap.get("changeAmount"));
//                        String straightDepositStr = accountHeadMapperEx.getDepositByLinkNumber(dh.getNumber(), "3");
//                        dh.setStraightDepositStr(straightDepositStr);
                        //预收找零
                        dh.setDepositChange((BigDecimal)depositMap.get("change"));
                        Map<String, Object> paymentMap  = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "6");
                        //实际收款
                        dh.setActualPayment((BigDecimal)paymentMap.get("changeAmount"));
//                        String paymentSalesOut = accountHeadMapperEx.getDepositByHeadLinkNumber(dh.getNumber(), "6");
//                        dh.setPaymentSalesOut(paymentSalesOut);
                        //收款找零
                        dh.setPayChange((BigDecimal)paymentMap.get("change"));
                        //抵扣
                        dh.setDeduction((BigDecimal)paymentMap.get("deduction"));
                        BigDecimal receivable = accountHeadMapperEx.getPaymentByHeadLinkNumber(dh.getNumber(), "6","1");
                        dh.setReceivable(receivable);
                        //收款
                        dh.setCollection((String) paymentMap.get("payment"));
                        dh.setAccountingLoginName((String)paymentMap.get("accountingLoginName"));
                        dh.setAccountingUserName((String) paymentMap.get("accountingUserName"));

                        BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByNumber(dh.getNumber());
                        dh.setRefundsDiscountLastMoney(refundsByNumber);
                    }
                    if ("下达采购".equals(dh.getSubType())){
                        dh.setStraightDeposit(accountHeadMapperEx.getDepositByNumber(dh.getNumber(),"2"));
                    }
                    if ("采购订单".equals(dh.getSubType())){
                        dh.setStraightDeposit(accountHeadMapperEx.getDepositByNumber(dh.getNumber(),"1"));
                    }
                    if ("销售订单".equals(dh.getSubType())){
                        Map<String, Object> depositMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "4");
                        //订金
                        dh.setStraightDeposit((BigDecimal)depositMap.get("changeAmount"));
//                        String straightDepositStr = accountHeadMapperEx.getDepositByLinkNumber(dh.getNumber(), "4");
//                        dh.setStraightDepositStr(straightDepositStr);
                        //预收找零
                        dh.setDepositChange((BigDecimal)depositMap.get("change"));
                        Map<String, Object> paymentMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "5");
                        //实际收款
                        dh.setActualPayment((BigDecimal)paymentMap.get("changeAmount"));
//                        String paymentSalesOut = accountHeadMapperEx.getDepositByHeadLinkNumber(dh.getNumber(), "5");
//                        dh.setPaymentSalesOut(paymentSalesOut);
                        //收款找零
                        dh.setPayChange((BigDecimal)paymentMap.get("change"));
                        //抵扣
                        dh.setDeduction((BigDecimal)paymentMap.get("deduction"));
                        //收款
                        BigDecimal receivable = accountHeadMapperEx.getPaymentByHeadLinkNumber(dh.getNumber(), "5","1");
                        dh.setCollection((String)paymentMap.get("payment"));
                        dh.setReceivable(receivable);
                        dh.setAccountingLoginName((String)paymentMap.get("accountingLoginName"));
                        dh.setAccountingUserName((String) paymentMap.get("accountingUserName"));

                        BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByNumber(dh.getNumber());
                        dh.setRefundsDiscountLastMoney(refundsByNumber);
                    }
                    if ("销售".equals(dh.getSubType()) || "销售退货".equals(dh.getSubType())){
                        PaymentVo payment = accountHeadService.getPaymentByBillIdNotAccountName(dh.getId(), "5");
                        if (payment!=null){
                            dh.setReceivable(payment.getPayment());
                            dh.setAccountingLoginName(payment.getAccountingLoginName());
                            dh.setAccountingUserName(payment.getAccountingUserName());
                        }
                        if ("销售".equals(dh.getSubType())){
                            BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByOutNumber(dh.getNumber());
                            dh.setRefundsDiscountLastMoney(refundsByNumber);
                        }
                    }
                    if ("厂家到货".equals(dh.getSubType())){
                        PaymentVo payment = accountHeadService.getPaymentByBillIdNotAccountName(dh.getId(), "6");
                        if (payment!=null){
                            dh.setReceivable(payment.getPayment());
                            dh.setAccountingLoginName(payment.getAccountingLoginName());
                            dh.setAccountingUserName(payment.getAccountingUserName());
                        }
                    }
//                    if ("销售".equals(dh.getSubType())){
//                        List<String> depositStr = accountHeadMapperEx.getCustom2ByBillId(dh.getId(), "5");
//                        List<String> strList=new ArrayList<>();
//                        if (depositStr!=null && depositStr.size()>0){
//                            for (String deposit:depositStr){
//                                List<String> list1 = StringUtil.strToStringList(deposit);
//                                if (list1 !=null && list1.size()>0){
//                                    strList.addAll(list1);
//                                }
//                            }
//                        }
//                        if (strList.size() > 0){
//                            String straightDepositStr = accountHeadMapperEx.getDepositByCustom2(strList);
//                            dh.setStraightDepositStr(straightDepositStr);
//                        }
//                        String paymentSalesOut = accountHeadMapperEx.getPaymentByBillId(dh.getId(), "5");
//                        dh.setPaymentSalesOut(paymentSalesOut);
//                    }
//                    if ("厂家到货".equals(dh.getSubType())){
//                        List<String> depositStr = accountHeadMapperEx.getCustom2ByBillId(dh.getId(), "6");
//                        List<String> strList=new ArrayList<>();
//                        if (depositStr!=null && depositStr.size()>0){
//                            for (String deposit:depositStr){
//                                List<String> list1 = StringUtil.strToStringList(deposit);
//                                if (list1 !=null &&list1.size()>0){
//                                    strList.addAll(list1);
//                                }
//                            }
//                        }
//                        if (strList.size() > 0){
//                            String straightDepositStr = accountHeadMapperEx.getDepositByCustom2(strList);
//                            dh.setStraightDepositStr(straightDepositStr);
//                        }
//                        String paymentSalesOut = accountHeadMapperEx.getPaymentByBillId(dh.getId(), "6");
//                        dh.setPaymentSalesOut(paymentSalesOut);
//                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    dh.setTotal(depotHeadMapperEx.getTotal(dh.getDefaultNumber()));
//                    dh.setFinishDebt(accountItemService.getEachAmountByBillId(dh.getId()));
                    if (StringUtils.isNotEmpty(dh.getDefaultNumber())){
                        String goToType = "";
                        if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(dh.getSubType())) {
                            goToType = BusinessConstants.SUB_TYPE_PURCHASE;
                        }
                        if ("厂家直发".equals(dh.getSubType())) {
                            goToType = "厂家到货";
                        }
                        if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(dh.getSubType())) {
                            goToType = BusinessConstants.SUB_TYPE_SALES;
                        }
                        BigDecimal receivedQuantity = depotHeadMapperEx.getReceivedQuantity(dh.getDefaultNumber(), goToType);
                        BigDecimal outCount = depotHeadMapperEx.getSalesReturnQuantity(dh.getDefaultNumber());
                        if (receivedQuantity ==null || outCount ==null){
                            dh.setReceivedQuantity(receivedQuantity);
                        }else {
                            receivedQuantity= receivedQuantity.subtract(outCount);
                            dh.setReceivedQuantity(receivedQuantity);
                        }
                    }
                    Integer approveProcess = workflowApproveDetailMapperEx.getBillProcessByNumber(dh.getNumber());
                    if (approveProcess != null) {
                        dh.setProcess(approveProcess);
                    } else {
                        dh.setProcess(workflowProcessDetailMapperEx.getBillProcessByNumber(dh.getNumber()));
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public Long countDepotHead(String type, String subType, String roleType, String status, String purchaseStatus, String number, String linkNumber,
                               String beginTime, String endTime, String materialParam, String organId, String creator, String depotId,
                               String accountId, String remark,String custom3, String payStatus, String freightStatus, String quotationStatus,
                               String custom4,String color,String alwaysSelect,String itemType,String creditStatus,String depotStatus) throws Exception {
        Long result = null;
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] depotArray = getDepotArray(subTypeList);
            String[] depotArrays = getDepotArrayByDepotStatus(depotStatus);
            String[] creatorArray = getCreatorArray(roleType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            String[] quotationStatusArray = StringUtil.isNotEmpty(quotationStatus) ? quotationStatus.split(",") : null;
            String[] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            result = depotHeadMapperEx.countsByDepotHead(typeList, subTypeList, creatorArray, statusArray, purchaseStatusArray, number, linkNumber, beginTime, endTime,
                    materialParam, organId, creator, depotId, depotArray, accountId, remark,custom3, payStatus,
                    freightStatus,quotationStatusArray,custom4,color,alwaysSelect,itemType,creditStatus,depotStatus,depotArrays);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
     * 根据单据类型获取仓库数组
     *
     * @param subTypeList
     * @return
     * @throws Exception
     */
    public String[] getDepotArray(List<String> subTypeList) throws Exception {
        String[] depotArray = null;
//        if (null != subTypeList && subTypeList.size() > 0) {
//            for (String subType : subTypeList) {
//                if (!BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(subType)
//                        && !BusinessConstants.SUB_TYPE_SALES_ORDER.equals(subType)
//                        && !"厂家直发".equals(subType) && !"下达采购".equals(subType)
//                        && !"厂家到货".equals(subType) && !"收费确认".equals(subType)
//                        && !"厂家报价".equals(subType) && !"直发厂家报价".equals(subType)
//                        && !"直发采购退货".equals(subType) && !"直发销售退货".equals(subType)
//                        && !"要货申请".equals(subType) && !"配送".equals(subType)
//                        && !"验收".equals(subType) && !"期初库存".equals(subType)){
//                    String depotIds = depotService.findDepotStrByCurrentUser();
//                    depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
//                }
//            }
//        }
        return depotArray;
    }
    public String[] getDepotArrayByDepotStatus(String depotStatus) throws Exception {
        String[] depotArray = null;
        if (StringUtil.isNotEmpty(depotStatus)) {
            String depotIds = depotService.findDepotStrByCurrentUser();
            depotArray = StringUtil.isNotEmpty(depotIds) ? depotIds.split(",") : null;
        }
        return depotArray;
    }

    /**
     * 根据角色类型获取操作员数组
     *
     * @param roleType
     * @return
     * @throws Exception
     */
    public String[] getCreatorArray(String roleType) throws Exception {
        String creator = getCreatorByRoleType(roleType);
        String[] creatorArray = null;
        if (StringUtil.isNotEmpty(creator)) {
            creatorArray = creator.split(",");
        }
        return creatorArray;
    }

    /**
     * 根据角色类型获取操作员
     *
     * @param roleType
     * @return
     * @throws Exception
     */
    public String getCreatorByRoleType(String roleType) throws Exception {
        String creator = "";
        User user = userService.getCurrentUser();
        if (BusinessConstants.ROLE_TYPE_PRIVATE.equals(roleType)) {
            creator = user.getId().toString();
        } else if (BusinessConstants.ROLE_TYPE_THIS_ORG.equals(roleType)) {
            creator = orgaUserRelService.getUserIdListByUserId(user.getId());
        }
        return creator;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDepotHead(JSONObject obj, HttpServletRequest request) throws Exception {
        DepotHead depotHead = JSONObject.parseObject(obj.toJSONString(), DepotHead.class);
        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setUploadFlag("0");
        int result = 0;
        try {
            result = depotHeadMapper.insertSelective(depotHead);
            logService.insertLog("单据", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDepotHead(JSONObject obj, HttpServletRequest request) throws Exception {
        DepotHead depotHead = JSONObject.parseObject(obj.get("info").toString(), DepotHead.class);
        DepotHead deleteDepotHead = getDepotHeadById(depotHead.getId());
        if ("1".equals(deleteDepotHead.getDeleteFlag())){
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DELETE_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_DELETE_MSG : ExceptionConstants.DEPOT_HEAD_DELETE_MSG_US);
        }
        depotHead.setUploadFlag("0");
        if (StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
            depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
        }
        if (StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
            //校验多账户的结算金额
            String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
            String[] split = accountMoneyList.split(",");
            BigDecimal sum = StringUtil.getArrSum(split);
            BigDecimal manyAccountSum = sum.abs();
            if (manyAccountSum.compareTo(depotHead.getTotalPrice().abs()) != 0) {
                logger.error("=========================================");
                logger.error("多账户各项金额："+ Arrays.toString(split));
                logger.error("收款总金额："+manyAccountSum);
                logger.error("单据总金额："+depotHead.getTotalPrice().abs());
                logger.error("=========================================");
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US);
            }
            depotHead.setAccountMoneyList(accountMoneyList);
        }
        int result = 0;
        try {
            result = depotHeadMapper.updateByPrimaryKeySelective(depotHead);
//            if("零售销售".equals(depotHead.getSubType()) && "1".equals(depotHead.getStatus())){
//                //更新当前库存
//                depotItemService.updateCurrentStockByHeaderId(depotHead.getId());
//            }
            logService.insertLog("单据",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getId()).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDepotHead(String id, HttpServletRequest request) throws Exception {
        return batchDeleteBillByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotHead(String ids, HttpServletRequest request) throws Exception {
        return batchDeleteBillByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteBillByIds(String ids) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<DepotHead> dhList = getDepotHeadListByIds(ids);
        for (DepotHead depotHead : dhList) {
            sb.append("[").append(depotHead.getNumber()).append("]");
            //只有未审核的单据才能被删除
            if ("0".equals(depotHead.getStatus())) {
                User userInfo = userService.getCurrentUser();
                List<DepotItem> list = depotItemService.getListByHeaderId(depotHead.getId());
                //删除单据子表数据
                depotItemMapperEx.batchDeleteDepotItemByDepotHeadIds(new String[]{depotHead.getId()});
                //删除单据附件
                attachmentMapperEx.batchDeleteAttachmentByHeadId(new Date(), userInfo == null ? null : userInfo.getId(), new String[]{depotHead.getId()});
                //删除待审批任务
                workflowProcessDetailMapperEx.batchDeleteByBillId(new String[]{depotHead.getNumber()});
                //删除单据主表信息
                batchDeleteDepotHeadByIds(depotHead.getId().toString());
                //将关联的单据置为审核状态-针对采购入库、销售出库和盘点复盘
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    if ((BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
                            BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
                            BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
                            BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
                            "收费确认".equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_AOG.equals(depotHead.getType()) &&
                            "厂家到货".equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
                            "配送".equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
                            "验收".equals(depotHead.getSubType()))
                            ) {
                        String status = BusinessConstants.BILLS_STATUS_AUDIT;
                        //查询除当前单据之外的关联单据列表
                        List<DepotHead> exceptCurrentList = getListByLinkNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber(), depotHead.getType());
                        if (exceptCurrentList != null && exceptCurrentList.size() > 0) {
                            status = BusinessConstants.BILLS_STATUS_SKIPING;
                        }
                        DepotHead dh = new DepotHead();
                        dh.setStatus(status);
                        dh.setUploadFlag("0");
                        DepotHeadExample example = new DepotHeadExample();
                        example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
                        depotHeadMapper.updateByExampleSelective(dh, example);
                    }else if ((BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
                            "零售退货".equals(depotHead.getSubType()))
                            || (BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
                            "仓库退货".equals(depotHead.getSubType()))) {
                        DepotHead dh = new DepotHead();
                        dh.setCustom4(BusinessConstants.BILLS_STATUS_SKIPING);
                        dh.setUploadFlag("0");
                        DepotHeadExample example = new DepotHeadExample();
                        example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
                        depotHeadMapper.updateByExampleSelective(dh, example);
                    }else if((BusinessConstants.DEPOTHEAD_TYPE_IN.equals(depotHead.getType()) &&
                            "其它".equals(depotHead.getSubType()))
                    ||(BusinessConstants.DEPOTHEAD_TYPE_OUT.equals(depotHead.getType()) &&
                            "其它".equals(depotHead.getSubType()))){
                        //更新盘点单的明细
                        DepotItem di = new DepotItem();
                        di.setUploadFlag("0");
                        di.setCustom12(0);
                        DepotItemExample example = new DepotItemExample();
                        List<String> idList = new ArrayList<>();
                        list.forEach(depotItem -> {
                            idList.add(depotItem.getId());
                        });
                        example.createCriteria().andIdIn(idList);
                        depotItemMapper.updateByExampleSelective(di, example);

                        String status = BusinessConstants.BILLS_STATUS_AUDIT;
                        //查询除当前单据之外的关联单据列表
                        List<DepotHead> exceptCurrentList = getListByLinkNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber(),BusinessConstants.DEPOTHEAD_TYPE_IN+","+BusinessConstants.DEPOTHEAD_TYPE_OUT);
                        if (exceptCurrentList != null && exceptCurrentList.size() > 0) {
                            status = BusinessConstants.BILLS_STATUS_SKIPING;
                        }
                        DepotHead dh = new DepotHead();
                        dh.setStatus(status);
                        dh.setUploadFlag("0");
                        DepotHeadExample depotHeadExample = new DepotHeadExample();
                        depotHeadExample.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
                        depotHeadMapper.updateByExampleSelective(dh, depotHeadExample);
                    }
                }
                if ( "销售退货".equals(depotHead.getSubType()) ) {
                    if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                        String billStatus = depotItemService.getBillStatusByParam(depotHead);
                        depotItemService.changeSaleStatus(depotHead, billStatus);
                    }
                }
                //将关联的销售订单单据置为未采购状态-针对销售订单转采购订单的情况
                if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                    if (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHead.getType()) &&
                            (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType()) || "下达采购".equals(depotHead.getSubType()))) {
                        DepotHead dh = new DepotHead();
                        dh.setUploadFlag("0");
                        //获取分批操作后单据的商品和商品数量（汇总）
                        List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(depotHead.getLinkNumber(), depotHead.getType(),depotHead.getSubType());
                        if (batchList.size() > 0) {
                            dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_SKIPING);
                        } else {
                            dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
                        }
                        DepotHeadExample example = new DepotHeadExample();
                        example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
                        depotHeadMapper.updateByExampleSelective(dh, example);
                    }
                }
//                //更新当前库存
//                for (DepotItem depotItem : list) {
//                    depotItem.setUploadFlag("0");
//                    depotItemService.updateCurrentStock(depotItem);
//                }
            } else {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_UN_AUDIT_DELETE_FAILED_MSG_US));
            }
        }
        logService.insertLog("单据", sb.toString(), StringUtil.getRequest());
        return 1;
    }

    /**
     * 删除单据主表信息
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDepotHeadByIds(String ids) throws Exception {
        User userInfo = userService.getCurrentUser();
        String[] idArray = ids.split(",");
        int result = 0;
        try {
            result = depotHeadMapperEx.batchDeleteDepotHeadByIds(new Date(), userInfo == null ? null : userInfo.getId(), idArray);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHead> getDepotHeadListByIds(String ids) throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<DepotHead> list = new ArrayList<>();
        try {
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andIdIn(idList);
            list = depotHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public DepotHead getDepotHeadByIds(String id) throws Exception {
        DepotHead head = null;
        try {
            head = depotHeadMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (head != null) {
            if (head.getPurchaseStatus().equals("2")) {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_TWO_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_PURCHASE_TWO_MSG : ExceptionConstants.DEPOT_HEAD_PURCHASE_TWO_MSG_US, head.getNumber()));
            }
            if (head.getStatus().equals("0")) {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NOT_AUDIT_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NOT_AUDIT_MSG : ExceptionConstants.DEPOT_HEAD_NOT_AUDIT_MSG_US, head.getNumber()));
            }
            if (!head.getSubType().equals("厂家直发")) {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_NOT_YYL_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_NOT_YYL_MSG : ExceptionConstants.DEPOT_HEAD_NOT_YYL_MSG_US, head.getNumber()));
            }
        }

        return head;
    }

    public int checkIsNameExist(String id, String name) throws Exception {
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = null;
        try {
            list = depotHeadMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list == null ? 0 : list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(String status, String depotHeadIDs) throws Exception {
        int result = 0;
        List<String> dhIds = new ArrayList<>();
        List<String> ids = StringUtil.strToStringList(depotHeadIDs);
        for (String id : ids) {
            DepotHead depotHead = getDepotHeadById(id);
            if ("0".equals(status)) {
                if ("1".equals(depotHead.getStatus())) {
                    dhIds.add(id);
                } else {
                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG_US));
                }
            } else if ("1".equals(status) || "4".equals(status)) {
                if ("0".equals(depotHead.getStatus())) {
                    dhIds.add(id);
                } else {
                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_UN_AUDIT_TO_AUDIT_FAILED_MSG_US));
                }
            }
        }
        if (dhIds.size() > 0) {
            DepotHead depotHead = new DepotHead();
            depotHead.setStatus(status);
            depotHead.setUploadFlag("0");
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andIdIn(dhIds);
            result = depotHeadMapper.updateByExampleSelective(depotHead, example);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchCounterAuditStatus(String depotHeadIDs) throws Exception {
        int result = 0;
        List<String> dhIds = new ArrayList<>();
        List<String> ids = StringUtil.strToStringList(depotHeadIDs);
        for (String id : ids) {
            DepotHead depotHead = getDepotHeadById(id);
            if ("1".equals(depotHead.getStatus()) || "3".equals(depotHead.getStatus())|| "2".equals(depotHead.getStatus()) ) {
                switch (depotHead.getStatus()) {
                    case "1":
                    case "2":
                    case "3":
                        //查询是否有下游单据
                        DepotHeadExample example = new DepotHeadExample();
                        example.createCriteria().andLinkNumberEqualTo(depotHead.getNumber())
                                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                        List<DepotHead> headList = depotHeadMapper.selectByExample(example);
                        if (null != headList && headList.size() > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.COUNTER_AUDIT_FAIL_CODE,
                                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.COUNTER_AUDIT_FAIL_MSG : ExceptionConstants.COUNTER_AUDIT_FAIL_US);
                        }
                        //查询表头关联订单
                        AccountHeadExample numberExample = new AccountHeadExample();
                        numberExample.createCriteria().andNumberEqualTo(depotHead.getNumber())
                                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                        List<AccountHead> numberAccount = accountHeadMapper.selectByExample(numberExample);
                        if (null != numberAccount && numberAccount.size() > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.COUNTER_AUDIT_FAIL_CODE,
                                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.COUNTER_AUDIT_FAIL_MSG : ExceptionConstants.COUNTER_AUDIT_FAIL_US);
                        }
                        //查询运费单表头关联的入库
                        AccountHeadExample customExample = new AccountHeadExample();
                        customExample.createCriteria().andNumberEqualTo(depotHead.getNumber())
                                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                        List<AccountHead> customAccount = accountHeadMapper.selectByExample(customExample);
                        if (null != customAccount && customAccount.size() > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.COUNTER_AUDIT_FAIL_CODE,
                                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.COUNTER_AUDIT_FAIL_MSG : ExceptionConstants.COUNTER_AUDIT_FAIL_US);
                        }
                        //查询收付款明细关联的出入库
                        AccountItemExample itemExample = new AccountItemExample();
                        itemExample.createCriteria().andBillIdEqualTo(id)
                                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
                        List<AccountItem> accountItems = accountItemMapperEx.getHeadByBillId(id);
                        if (null != accountItems && accountItems.size() > 0) {
                            throw new BusinessRunTimeException(ExceptionConstants.COUNTER_AUDIT_FAIL_CODE,
                                    "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.COUNTER_AUDIT_FAIL_MSG : ExceptionConstants.COUNTER_AUDIT_FAIL_US);
                        }
                        dhIds.add(id);
                        break;
                    default:
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
                                "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG_US);
                }
            } else {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG_US));
            }
        }
        if (dhIds.size() > 0) {
            DepotHead depotHead = new DepotHead();
            depotHead.setStatus("0");
            depotHead.setUploadFlag("0");
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andIdIn(dhIds);
            result = depotHeadMapper.updateByExampleSelective(depotHead, example);
            for (String id : dhIds) {
                DepotHead depotHeadById = getDepotHeadById(id);
                //更新当前库存
                depotItemService.updateCurrentStockByHeaderId(depotHeadById.getId(),false);
                //修改关联订单状态
                changeBillStatus(depotHeadById.getId());
                //盘点单状态
                depotItemService.getTakeStockDepotHead(depotHeadById.getId());

//                //将关联的销售订单单据置为未采购状态-针对销售订单转采购订单的情况
//                if (StringUtil.isNotEmpty(depotHeadById.getLinkNumber())) {
//                    if (BusinessConstants.DEPOTHEAD_TYPE_OTHER.equals(depotHeadById.getType()) &&
//                        (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHeadById.getSubType()) || "下达采购".equals(depotHeadById.getSubType()))) {
//                        DepotHead dh = new DepotHead();
//                        dh.setUploadFlag("0");
//                        //获取分批操作后单据的商品和商品数量（汇总）
//                        List<DepotItemVo4MaterialAndSum> batchList = depotItemMapperEx.getBatchBillDetailMaterialSum(depotHeadById.getLinkNumber(), depotHeadById.getType(),depotHeadById.getSubType());
//                        if (batchList.size() > 0) {
//                            dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_SKIPING);
//                        } else {
//                            dh.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
//                        }
//                        DepotHeadExample example = new DepotHeadExample();
//                        example.createCriteria().andNumberEqualTo(depotHead.getLinkNumber());
//                        depotHeadMapper.updateByExampleSelective(dh, example);
//                    }
//                }
            }

        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchEndStatus(String depotHeadIDs) throws Exception {
        int result = 0;
        List<String> dhIds = new ArrayList<>();
        List<String> ids = StringUtil.strToStringList(depotHeadIDs);
        for (String id : ids) {
            DepotHead depotHead = getDepotHeadById(id);
            if ("1".equals(depotHead.getStatus()) || "3".equals(depotHead.getStatus())) {
                dhIds.add(id);
            } else {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_AUDIT_TO_UN_AUDIT_FAILED_MSG_US));
            }
        }
        if (dhIds.size() > 0) {
            DepotHead depotHead = new DepotHead();
            depotHead.setStatus("2");
            depotHead.setUploadFlag("0");
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andIdIn(dhIds);
            result = depotHeadMapper.updateByExampleSelective(depotHead, example);
        }
        return result;
    }
    public String findMaterialsListByHeaderId(String id) throws Exception {
        String result = null;
        try {
            result = depotHeadMapperEx.findMaterialsListByHeaderId(id);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4InDetail> findByAll(String beginTime, String endTime, String type, String materialParam,
                                                List<String> depotList, String oId, String number, String remark, Integer offset,
                                                Integer rows,String flag,String subType,String creator,String otherStatus,List<String> idList) throws Exception {
        List<DepotHeadVo4InDetail> list = null;
        List<DepotHeadVo4InDetail> resList = new ArrayList<>();
        try {
            list = depotHeadMapperEx.findByAll(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, offset, rows,flag,subType,creator,otherStatus,idList);
            if (null != list && list.size() > 0) {
                for (DepotHeadVo4InDetail m : list) {
                    if (m.getAllPrice() ==null){
                        m.setAllPrice(m.getPurchaseDecimal().multiply(m.getOperNumber()));
                    }
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public int findByAllCount(String beginTime, String endTime, String type, String materialParam,
                              List<String> depotList, String oId, String number, String remark,String flag,
                              String subType,String creator,String otherStatus,List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findByAllCount(beginTime, endTime, type, materialParam, depotList,
                    oId, number, remark,flag,subType,creator,otherStatus,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4InOutMCount> findInOutMaterialCount(String beginTime, String endTime, String type, String materialParam,
                                                                List<String> depotList, String oId, Integer offset, Integer rows,String flag,
                                                                List<String> idList) throws Exception {
        List<DepotHeadVo4InOutMCount> list = null;
        try {
            list = depotHeadMapperEx.findInOutMaterialCount(beginTime, endTime, type, materialParam, depotList, oId, offset, rows,flag,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int findInOutMaterialCountTotal(String beginTime, String endTime, String type, String materialParam,
                                           List<String> depotList, String oId,String flag,List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findInOutMaterialCountTotal(beginTime, endTime, type, materialParam, depotList, oId,flag,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4InOutMCount> findPromotionMaterialCount(String materialParam,
                                                                    List<String> depotList, List<String> idList,
                                                                    Integer offset, Integer rows) throws Exception {
        List<DepotHeadVo4InOutMCount> resList = new ArrayList<>();
        List<DepotHeadVo4InOutMCount> list = null;
        try {
            list = depotHeadMapperEx.findPromotionMaterialCount(materialParam, depotList, idList, offset, rows);
            if (null != list && list.size() > 0) {
                for (DepotHeadVo4InOutMCount m : list) {
                    m.setAveragePrice(m.getPriceSum().divide(m.getNumSum(), 2, BigDecimal.ROUND_UP));
                    m.setTaxAveragePrice(m.getPriceSum().divide(m.getNumSum(), 2, BigDecimal.ROUND_UP));
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public int findPromotionMaterialCountTotal(String materialParam, List<String> depotList, List<String> idList) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findPromotionMaterialCountTotal(materialParam, depotList, idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4InDetail> findAllocationDetail(String beginTime, String endTime, String subType, String number,
                                                           String materialParam, List<String> depotList, List<String> depotFList,
                                                           String remark, Integer offset, Integer rows,String creator,String materialId,
                                                           List<String> idList) throws Exception {
        List<DepotHeadVo4InDetail> list = null;
        List<DepotHeadVo4InDetail> resList = new ArrayList<>();
        try {
            List<String> subTypeList =new ArrayList<>();
            if ("调拨".equals(subType)){
//                subTypeList.add("要货申请");
                subTypeList.add("验收");
                subTypeList.add("配送");
            }else {
                subTypeList.add(subType);
            }
            list = depotHeadMapperEx.findAllocationDetail(beginTime, endTime, subTypeList, number,
                    materialParam, depotList, depotFList, remark, offset, rows,creator,materialId,idList);
            if (null != list && list.size() > 0) {
                for (DepotHeadVo4InDetail m : list) {
                    if (m.getPurchaseDecimal()!=null && m.getPurchaseDecimal().compareTo(BigDecimal.ZERO)>0){
                        m.setAllPrice(m.getPurchaseDecimal().multiply(m.getOperNumber()));
                    }
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public int findAllocationDetailCount(String beginTime, String endTime, String subType, String number,
                                         String materialParam, List<String> depotList, List<String> depotFList, String remark,
                                         String creator,String materialId,List<String> idList) throws Exception {
        int result = 0;
        try {
            List<String> subTypeList =new ArrayList<>();
            if ("调拨".equals(subType)){
//                subTypeList.add("要货申请");
                subTypeList.add("验收");
                subTypeList.add("配送");
            }else {
                subTypeList.add(subType);
            }
            result = depotHeadMapperEx.findAllocationDetailCount(beginTime, endTime, subTypeList, number, materialParam,
                    depotList, depotFList, remark,creator,materialId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4StatementAccount> getStatementAccount(String beginTime, String endTime, String organId, String supplierType,
                                                                  String type, String subType, Integer offset, Integer rows, String type1, String subType1,
                                                                  String accountType,Integer zeroAmount,String tenantId) {
        List<DepotHeadVo4StatementAccount> list = null;
        try {
            list = depotHeadMapperEx.getStatementAccount(beginTime, endTime, organId, supplierType, type, subType, offset, rows,
                    type1, subType1, accountType,zeroAmount,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public int getStatementAccountCount(String beginTime, String endTime, String organId, String supplierType,
                                        String type, String subType, String type1, String subType1, String accountType,
                                        Integer zeroAmount,String tenantId) {
        int result = 0;
        try {

            result = depotHeadMapperEx.getStatementAccountCount(beginTime, endTime, organId, supplierType, type, subType, type1, subType1,
                    accountType,zeroAmount,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadVo4StatementAccount> getStatementAccountTotalPay(String beginTime, String endTime, String organId, String supplierType,
                                                                          String type, String subType, String type1, String subType1, String accountType, String tenantId) {
        List<DepotHeadVo4StatementAccount> list = null;
        try {
            list = depotHeadMapperEx.getStatementAccountTotalPay(beginTime, endTime, organId, supplierType, type, subType, type1, subType1, accountType,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public BigDecimal findAllMoney(String supplierId, String type, String subType, String mode, String endTime, String type1, String subType1) throws Exception {
        String modeName = "";
        BigDecimal allOtherMoney = BigDecimal.ZERO;
        BigDecimal allDepositMoney = BigDecimal.ZERO;
        if (mode.equals("实际")) {
            modeName = "change_amount";
        } else if (mode.equals("合计")) {
            modeName = "discount_last_money";
            allOtherMoney = depotHeadMapperEx.findAllOtherMoney(supplierId, type, subType, endTime, type1, subType1);
            allDepositMoney = depotHeadMapperEx.findDepositMoney(supplierId, type, subType, endTime, type1, subType1);
        }
        BigDecimal result = BigDecimal.ZERO;
        try {
            result = depotHeadMapperEx.findAllMoney(supplierId, type, subType, modeName, endTime, type1, subType1);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (allOtherMoney != null) {
            result = result.add(allOtherMoney);
        }
        if (allDepositMoney != null) {
            result = result.subtract(allDepositMoney);
        }
        return result;
    }

    /**
     * 统计总金额
     *
     * @param getS
     * @param type
     * @param subType
     * @param mode    合计或者金额
     * @return
     */
    public BigDecimal allMoney(String getS, String type, String subType, String mode, String endTime, String type1, String subType1) {
        BigDecimal allMoney = BigDecimal.ZERO;
        try {
            BigDecimal sum = findAllMoney(getS, type, subType, mode, endTime, type1, subType1);
            if (sum != null) {
                allMoney = sum;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回正数，如果负数也转为正数
        if ((allMoney.compareTo(BigDecimal.ZERO)) == -1) {
            allMoney = allMoney.abs();
        }
        return allMoney;
    }

    /**
     * 查询单位的累计应收和累计应付，零售不能计入
     *
     * @param supplierId
     * @param endTime
     * @param supType
     * @return
     */
    public BigDecimal findTotalPay(String supplierId, String endTime, String supType) {
        BigDecimal sum = BigDecimal.ZERO;
//        String getS = supplierId.toString();
        if (("客户").equals(supType)) { //客户
            sum = allMoney(supplierId, "出库", "销售", "合计", endTime, "到货", "厂家到货").subtract(allMoney(supplierId, "出库", "销售", "实际", endTime, "到货", "厂家到货"));
        } else if (("供应商").equals(supType)) { //供应商
            sum = allMoney(supplierId, "入库", "采购", "合计", endTime, "其它", "收费确认").subtract(allMoney(supplierId, "入库", "采购", "实际", endTime, "其它", "收费确认"));
        }
        return sum;
    }

    public List<DepotHeadVo4List> getDetailByNumber(String number) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();
        List<DepotHeadVo4List> list = null;
        try {
//            Map<String, String> personMap = personService.getPersonMap();
            Map<String, String> accountMap = accountService.getAccountMap();
            list = depotHeadMapperEx.getDetailByNumber(number);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (accountMap != null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
                        String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
                        dh.setAccountName(accountStr);
                    }
                    if (dh.getAccountIdList() != null) {
                        String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountIdList(accountidlistStr);
                    }
                    if (dh.getAccountMoneyList() != null) {
                        String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountMoneyList(accountmoneylistStr);
                    }
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if (StringUtil.isNotEmpty(dh.getSalesMan())) {
                        User user = userService.getUser(dh.getSalesMan());
                        if (null !=user){
                            dh.setSalesManStr(user.getLoginName());
                            dh.setSalesUserName(user.getUsername());
                        }
//                        dh.setSalesManStr(personService.getPersonByMapAndIds(personMap, dh.getSalesMan()));
                    }
                    dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    if (StringUtil.isNotEmpty(dh.getCreator())){
                        User user = userService.getUser(dh.getCreator());
                        if (user != null) {
                            dh.setCreatorName(user.getLoginName());
                        }
                    }
                    if (StringUtils.isNotEmpty(dh.getLinkNumber()) && "下达采购".equals(dh.getSubType())){
                        dh.setClientName(depotHeadMapperEx.getClientNameByNumber(dh.getLinkNumber()));
                    }
                    if ("厂家直发".equals(dh.getSubType())){
                        Map<String, Object> depositMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "3");
                        //订金
                        dh.setStraightDeposit((BigDecimal) depositMap.get("changeAmount"));
//                        String straightDepositStr = accountHeadMapperEx.getDepositByLinkNumber(dh.getNumber(), "3");
//                        dh.setStraightDepositStr(straightDepositStr);
                        //预收找零
                        dh.setDepositChange((BigDecimal)depositMap.get("change"));
                        Map<String, Object> paymentMap  = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "6");
                        //实际收款
                        dh.setActualPayment((BigDecimal)paymentMap.get("changeAmount"));
//                        String paymentSalesOut = accountHeadMapperEx.getDepositByHeadLinkNumber(dh.getNumber(), "6");
//                        dh.setPaymentSalesOut(paymentSalesOut);
                        //收款找零
                        dh.setPayChange((BigDecimal)paymentMap.get("change"));
                        //抵扣
                        dh.setDeduction((BigDecimal)paymentMap.get("deduction"));
                        BigDecimal receivable = accountHeadMapperEx.getPaymentByHeadLinkNumber(dh.getNumber(), "6","1");
                        dh.setReceivable(receivable);
                        //收款
                        dh.setCollection((String) paymentMap.get("payment"));
                        dh.setAccountingLoginName((String)paymentMap.get("accountingLoginName"));
                        dh.setAccountingUserName((String) paymentMap.get("accountingUserName"));

                        BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByNumber(dh.getNumber());
                        dh.setRefundsDiscountLastMoney(refundsByNumber);
                    }
                    if ("下达采购".equals(dh.getSubType())){
                        dh.setStraightDeposit(accountHeadMapperEx.getDepositByNumber(dh.getNumber(),"2"));
                    }
                    if ("采购订单".equals(dh.getSubType())){
                        dh.setStraightDeposit(accountHeadMapperEx.getDepositByNumber(dh.getNumber(),"1"));
                    }
                    if ("销售订单".equals(dh.getSubType())){
                        Map<String, Object> depositMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "4");
                        //订金
                        dh.setStraightDeposit((BigDecimal)depositMap.get("changeAmount"));
//                        String straightDepositStr = accountHeadMapperEx.getDepositByLinkNumber(dh.getNumber(), "4");
//                        dh.setStraightDepositStr(straightDepositStr);
                        //预收找零
                        dh.setDepositChange((BigDecimal)depositMap.get("change"));
                        Map<String, Object> paymentMap = accountHeadMapperEx.getDepositChangeByNumber(dh.getNumber(), "5");
                        //实际收款
                        dh.setActualPayment((BigDecimal)paymentMap.get("changeAmount"));
//                        String paymentSalesOut = accountHeadMapperEx.getDepositByHeadLinkNumber(dh.getNumber(), "5");
//                        dh.setPaymentSalesOut(paymentSalesOut);
                        //收款找零
                        dh.setPayChange((BigDecimal)paymentMap.get("change"));
                        //抵扣
                        dh.setDeduction((BigDecimal)paymentMap.get("deduction"));
                        //收款
                        BigDecimal receivable = accountHeadMapperEx.getPaymentByHeadLinkNumber(dh.getNumber(), "5","1");
                        dh.setCollection((String)paymentMap.get("payment"));
                        dh.setReceivable(receivable);
                        dh.setAccountingLoginName((String)paymentMap.get("accountingLoginName"));
                        dh.setAccountingUserName((String) paymentMap.get("accountingUserName"));

                        BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByNumber(dh.getNumber());
                        dh.setRefundsDiscountLastMoney(refundsByNumber);
                    }
                    if ("销售".equals(dh.getSubType()) || "销售退货".equals(dh.getSubType())){
                        PaymentVo payment = accountHeadService.getPaymentByBillIdNotAccountName(dh.getId(), "5");
                        if (payment!=null){
                            dh.setReceivable(payment.getPayment());
                            dh.setAccountingLoginName(payment.getAccountingLoginName());
                            dh.setAccountingUserName(payment.getAccountingUserName());
                        }
                        if ("销售".equals(dh.getSubType())){
                            BigDecimal refundsByNumber = depotHeadMapperEx.getRefundsByOutNumber(dh.getNumber());
                            dh.setRefundsDiscountLastMoney(refundsByNumber);
                        }
                    }
                    if ("厂家到货".equals(dh.getSubType())){
                        PaymentVo payment = accountHeadService.getPaymentByBillIdNotAccountName(dh.getId(), "6");
                        if (payment!=null){
                            dh.setReceivable(payment.getPayment());
                            dh.setAccountingLoginName(payment.getAccountingLoginName());
                            dh.setAccountingUserName(payment.getAccountingUserName());
                        }
                    }

                    if (StringUtils.isNotEmpty(dh.getDefaultNumber())){
                        String goToType = "";
                        if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(dh.getSubType())) {
                            goToType = BusinessConstants.SUB_TYPE_PURCHASE;
                        }
                        if ("厂家直发".equals(dh.getSubType())) {
                            goToType = "厂家到货";
                        }
                        if (BusinessConstants.SUB_TYPE_SALES_ORDER.equals(dh.getSubType())) {
                            goToType = BusinessConstants.SUB_TYPE_SALES;
                        }
                        BigDecimal receivedQuantity = depotHeadMapperEx.getReceivedQuantity(dh.getDefaultNumber(), goToType);
                        BigDecimal outCount = depotHeadMapperEx.getSalesReturnQuantity(dh.getDefaultNumber());
                        if (receivedQuantity ==null || outCount ==null){
                            dh.setReceivedQuantity(receivedQuantity);
                        }else {
                            receivedQuantity= receivedQuantity.subtract(outCount);
                            dh.setReceivedQuantity(receivedQuantity);
                        }
                    }
                    Integer approveProcess = workflowApproveDetailMapperEx.getBillProcessByNumber(dh.getNumber());
                    if (approveProcess != null) {
                        dh.setProcess(approveProcess);
                    } else {
                        dh.setProcess(workflowProcessDetailMapperEx.getBillProcessByNumber(dh.getNumber()));
                    }
                    resList.add(dh);

                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    /**
     * 查询除当前单据之外的关联单据列表
     *
     * @param linkNumber
     * @param number
     * @return
     * @throws Exception
     */
    public List<DepotHead> getListByLinkNumberExceptCurrent(String linkNumber, String number, String type) throws Exception {
        DepotHeadExample example = new DepotHeadExample();
        List<String> typeList = StringUtil.strToStringList(type);
        example.createCriteria().andLinkNumberEqualTo(linkNumber).andNumberNotEqualTo(number).andTypeIn(typeList)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        return depotHeadMapper.selectByExample(example);
    }


    /**
     * 新增单据主表及单据子表信息
     *
     * @param beanJson
     * @param rows
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void addDepotHeadAndDetail(String beanJson, String rows, String attachment,
                                      HttpServletRequest request, boolean passDirect,
                                      String functionId) throws Exception {
        /**处理单据主表数据*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        depotHead.setId(IdUtils.getUUID());
        String subType = depotHead.getSubType();
        //结算账户校验
//        if ("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
//            if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
//                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
//                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG_US));
//            }
//        }
        //欠款校验
//        if ("采购退货".equals(subType) || "销售退货".equals(subType) || "零售退货".equals(subType) || "仓库退货".equals(subType) ) {
//            if (depotHead.getChangeAmount().abs().compareTo(depotHead.getDiscountLastMoney().add(depotHead.getOtherMoney())) != 0) {
//                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_CODE,
//                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_MSG_US));
//            }
//        }
        if ("销售订单".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)
                ||  "厂家直发".equals(subType) ||  "厂家到货".equals(subType) ||  "直发销售退货".equals(subType) ) {
           depotHead.setCustom12(0);
        }
        if ("要货申请".equals(subType) || "配送".equals(subType) || "验收".equals(subType)) {
            if (StringUtil.isEmpty(depotHead.getDepotId()) || StringUtil.isEmpty(depotHead.getAnotherDepotId())) {
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "要货申请仓库不能为空" : "The warehouse for requesting goods cannot be empty");
            }
        }
        //判断用户是否已经登录过，登录过不再处理
//        User userInfo = userService.getCurrentUser();
//        depotHead.setCreator(userInfo == null ? null : userInfo.getId());
        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if (StringUtil.isEmpty(depotHead.getStatus())) {
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        }
        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setPayType(depotHead.getPayType() == null ? "现付" : depotHead.getPayType());
        if (StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
            depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
        }
        if (StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
            //校验多账户的结算金额
            String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
            BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
            BigDecimal manyAccountSum = sum.abs();
            if (manyAccountSum.compareTo(depotHead.getTotalPrice().abs()) != 0) {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US));
            }
            depotHead.setAccountMoneyList(accountMoneyList);
        }
        //校验累计扣除订金是否超出订单中的金额
        if (depotHead.getDeposit() != null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
            BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
            //订单中的订金金额
            BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
            if (changeAmount != null) {
                BigDecimal preDeposit = changeAmount.abs();
                if (depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit) > 0) {
                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG : ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG_US));
                }
            }
        }
        try {
            depotHead.setUploadFlag("0");
            //防止复制单据时 不把租户字段删除的**
            if (!"盘点单".equals(depotHead.getSubType())){
                depotHead.setTenantId(null);
            }
            if (StringUtil.isEmpty(depotHead.getCustom5())){
                depotHead.setCustom5(null);
            }
            depotHeadMapper.insertSelective(depotHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        /**入库和出库处理预付款信息*/
//        if (BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())) {
//            if (depotHead.getOrganId() != null) {
//                BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
//                if (currentAdvanceIn.compareTo(depotHead.getTotalPrice()) >= 0) {
//                    supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice()));
//                } else {
//                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
//                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG : ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG_US));
//                }
//            }
//        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if (list != null) {
            String headId = list.get(0).getId();
            String depotId = list.get(0).getDepotId();
            String anotherDepotId = list.get(0).getAnotherDepotId();
            /**入库和出库处理单据子表信息*/
            depotItemService.saveDetials(rows, headId, "add", request, false);
            /**处理文件**/
            attachmentService.saveAttachment(attachment, depotHead.getId(), request);
        }
        logService.insertLog("单据",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(depotHead.getNumber()).toString(),
                StringUtil.getRequest());

        if (passDirect) {
            String keyId = userBusinessService.checkValueExist("ConfigRoleFunctions", "[" + functionId + "]", request);
            if (StringUtils.isNotEmpty(keyId)) {
                workflowConfigService.addProcessDetailWithDepot(keyId, depotHead);
            } else {
                depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
                depotHead.setUploadFlag("0");
                depotHeadMapper.updateByPrimaryKeySelective(depotHead);
                //更新当前库存
                depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
                //修改关联订单状态
                changeBillStatus(depotHead.getId());
                //盘点单状态
                depotItemService.getTakeStockDepotHead(depotHead.getId());
            }
        }

    }
    /**
    * @Author: wy
    * @Description: 已审核后修改关联订单的状态
    * @DateTime: 2023-02-10 16:36
    * @Params:
    * @Return
    */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void changeBillStatus(String headerId) throws Exception {
        DepotHead depotHead = getDepotHeadById(headerId);
        //如果关联单据号非空则更新订单的状态,单据类型：采购入库单或销售出库单或盘点复盘单
        if (BusinessConstants.SUB_TYPE_PURCHASE.equals(depotHead.getSubType())
                || BusinessConstants.SUB_TYPE_SALES.equals(depotHead.getSubType())
                || BusinessConstants.SUB_TYPE_REPLAY.equals(depotHead.getSubType())
                || "厂家到货".equals(depotHead.getSubType()) || "收费确认".equals(depotHead.getSubType())
                || "配送".equals(depotHead.getSubType()) || "验收".equals(depotHead.getSubType())) {
            if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                //单据状态:是否全部完成 2-全部完成 3-部分完成（针对订单的分批出入库）
                String billStatus = depotItemService.getBillStatusByParam(depotHead);
                depotItemService.changeBillStatus(depotHead, billStatus);
            }
        }
        //如果关联单据号非空则更新订单的状态,此处针对销售订单转采购订单的场景
        if (BusinessConstants.SUB_TYPE_PURCHASE_ORDER.equals(depotHead.getSubType())
                || "下达采购".equals(depotHead.getSubType())) {
            if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                String billStatus = depotItemService.getBillStatusByParam(depotHead);
                depotItemService.changeBillPurchaseStatus(depotHead, billStatus);
            }
        }
        //如果关联单据号非空则更新订单的状态,此处针对仓库和销售退货
        if ("零售退货".equals(depotHead.getSubType()) || "仓库退货".equals(depotHead.getSubType())) {
            if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
                String billStatus = depotItemService.getBillStatusByParam(depotHead);
                depotItemService.changeSaleStatus(depotHead, billStatus);
            }
        }
        //如果关联单据号非空则更新订单的状态,此处销售退货， 如果是换货的话需要修改订单状态
        if ( "销售退货".equals(depotHead.getSubType()) ) {
//            if (StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
//                String billStatus = depotItemService.getBillStatusByParam(depotHead);
//                depotItemService.changeSaleStatus(depotHead, billStatus);
//            }
            DepotHead depotHead1 = getDepotHead(depotHead.getLinkNumber());
            if (StringUtil.isNotEmpty(depotHead1.getLinkNumber())){
                String billStatus = depotItemService.getBillStatusByParam(depotHead1);
                depotItemService.changeSaleStatus(depotHead1, billStatus);
            }
        }
    }

    /**
     * 更新单据主表及单据子表信息
     *
     * @param beanJson
     * @param rows
     * @param request
     * @throws Exception
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void updateDepotHeadAndDetail(String beanJson, String rows, String attachment, HttpServletRequest request, boolean passDirect,
                                         String functionId) throws Exception {
        /**更新单据主表信息*/
        DepotHead depotHead = JSONObject.parseObject(beanJson, DepotHead.class);
        //获取之前的金额数据
//        BigDecimal preTotalPrice = getDepotHeadById(depotHead.getId()).getTotalPrice().abs();
        String subType = depotHead.getSubType();
        //结算账户校验
//        if ("采购".equals(subType) || "采购退货".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)) {
//            if (StringUtil.isEmpty(depotHead.getAccountIdList()) && depotHead.getAccountId() == null) {
//                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_CODE,
//                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ACCOUNT_FAILED_MSG_US));
//            }
//        }
        //欠款校验
//        if ("采购退货".equals(subType) || "销售退货".equals(subType) || "零售退货".equals(subType) || "仓库退货".equals(subType)) {
//            if (depotHead.getChangeAmount().abs().compareTo(depotHead.getDiscountLastMoney().add(depotHead.getOtherMoney())) != 0) {
//                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_CODE,
//                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_BACK_BILL_DEBT_FAILED_MSG_US));
//            }
//        }
        if ("要货申请".equals(subType) || "配送".equals(subType) || "验收".equals(subType)) {
            if (StringUtil.isEmpty(depotHead.getDepotId()) && StringUtil.isEmpty(depotHead.getAnotherDepotId())) {
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "要货申请仓库不能为空" : "The warehouse for requesting goods cannot be empty");
            }
        }
        if ("销售订单".equals(subType) || "销售".equals(subType) || "销售退货".equals(subType)
                ||  "厂家直发".equals(subType) ||  "厂家到货".equals(subType) ||  "直发销售退货".equals(subType)) {
            depotHead.setCustom12(0);
        }
        if (StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
            depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
        }
        if (StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
            //校验多账户的结算金额
            String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
            BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
            BigDecimal manyAccountSum = sum.abs();
            if (manyAccountSum.compareTo(depotHead.getTotalPrice().abs()) != 0) {
                throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
                        String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US));
            }
            depotHead.setAccountMoneyList(accountMoneyList);
        }
        //校验累计扣除订金是否超出订单中的金额
        if (depotHead.getDeposit() != null && StringUtil.isNotEmpty(depotHead.getLinkNumber())) {
            BigDecimal finishDeposit = depotHeadMapperEx.getFinishDepositByNumberExceptCurrent(depotHead.getLinkNumber(), depotHead.getNumber());
            //订单中的订金金额
            BigDecimal changeAmount = getDepotHead(depotHead.getLinkNumber()).getChangeAmount();
            if (changeAmount != null) {
                BigDecimal preDeposit = changeAmount.abs();
                if (depotHead.getDeposit().add(finishDeposit).compareTo(preDeposit) > 0) {
                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_CODE,
                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG : ExceptionConstants.DEPOT_HEAD_DEPOSIT_OVER_PRE_MSG_US));
                }
            }
        }
        try {
            depotHead.setUploadFlag("0");
            //防止复制单据时 不把租户字段删除的**
            if (!"盘点单".equals(depotHead.getSubType())){
                depotHead.setTenantId(null);
            }
            if (StringUtil.isEmpty(depotHead.getCustom5())){
                depotHead.setCustom5(null);
            }
            depotHeadMapper.updateByPrimaryKeySelective(depotHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        /**入库和出库处理预付款信息*/
//        if (BusinessConstants.PAY_TYPE_PREPAID.equals(depotHead.getPayType())) {
//            if (depotHead.getOrganId() != null) {
//                BigDecimal currentAdvanceIn = supplierService.getSupplier(depotHead.getOrganId()).getAdvanceIn();
//                if (currentAdvanceIn.compareTo(depotHead.getTotalPrice()) >= 0) {
//                    supplierService.updateAdvanceIn(depotHead.getOrganId(), BigDecimal.ZERO.subtract(depotHead.getTotalPrice().subtract(preTotalPrice)));
//                } else {
//                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_CODE,
//                            String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG : ExceptionConstants.DEPOT_HEAD_MEMBER_PAY_LACK_MSG_US));
//                }
//            }
//        }
        /**入库和出库处理单据子表信息*/
        depotItemService.saveDetials(rows, depotHead.getId(), "update", request, false);
        /**处理文件**/
        attachmentService.saveAttachment(attachment, depotHead.getId(), request);
        logService.insertLog("单据",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(depotHead.getNumber()).toString(),
                StringUtil.getRequest());
        if (passDirect && !depotHead.getSubType().equals("零售") && !depotHead.getSubType().equals("零售退货")) {
            WorkflowApproveDetailExample approveDetailExample = new WorkflowApproveDetailExample();
            approveDetailExample.createCriteria().andSysOwnerCpyEqualTo(depotHead.getId());
            workflowApproveDetailMapper.deleteByExample(approveDetailExample);
            String keyId = userBusinessService.checkValueExist("ConfigRoleFunctions", "[" + functionId + "]", request);
            if (StringUtils.isNotEmpty(keyId)) {
                workflowConfigService.addProcessDetailWithDepot(keyId, depotHead);
            } else {
                depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
                depotHead.setUploadFlag("0");
                depotHeadMapper.updateByPrimaryKeySelective(depotHead);
                //更新当前库存
                depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
                //修改关联订单状态
                changeBillStatus(depotHead.getId());
                //盘点单状态
                depotItemService.getTakeStockDepotHead(depotHead.getId());
            }
        }
    }

    public Map<String, Object> getBuyAndSaleStatistics(String today, String monthFirstDay, String yesterdayBegin, String yesterdayEnd, String yearBegin, String yearEnd) {
        Map<String, Object> map = new HashMap<>();
        //今日
        BigDecimal todayBuy = getBuyAndSaleBasicStatistics("入库", "采购",
                1, today, getNow3(),"其它","收费确认"); //今日采购入库
        BigDecimal todayBuyBack = getBuyAndSaleBasicStatistics("出库", "采购退货",
                1, today, getNow3(),"其它","直发采购退货"); //今日采购退货
        BigDecimal todaySale = getBuyAndSaleBasicStatistics("出库", "销售",
                1, today, getNow3(),"到货","厂家到货"); //今日销售出库
        BigDecimal todaySaleBack = getBuyAndSaleBasicStatistics("入库", "销售退货",
                1, today, getNow3(),"其它","直发销售退货"); //今日销售退货
        BigDecimal todayRetailSale = getBuyAndSaleRetailStatistics("出库", "零售",
                today, getNow3(),"出库","零售销售"); //今日零售出库
        BigDecimal todayRetailSaleBack = getBuyAndSaleRetailStatistics("入库", "零售退货",
                today, getNow3(),"入库","仓库退货"); //今日零售退货
        //本月
        BigDecimal monthBuy = getBuyAndSaleBasicStatistics("入库", "采购",
                1, monthFirstDay, getNow3(),"其它","收费确认"); //本月采购入库
        BigDecimal monthBuyBack = getBuyAndSaleBasicStatistics("出库", "采购退货",
                1, monthFirstDay, getNow3(),"其它","直发采购退货"); //本月采购退货
        BigDecimal monthSale = getBuyAndSaleBasicStatistics("出库", "销售",
                1, monthFirstDay, getNow3(),"到货","厂家到货"); //本月销售出库
        BigDecimal monthSaleBack = getBuyAndSaleBasicStatistics("入库", "销售退货",
                1, monthFirstDay, getNow3(),"其它","直发销售退货"); //本月销售退货
        BigDecimal monthRetailSale = getBuyAndSaleRetailStatistics("出库", "零售",
                monthFirstDay, getNow3(),"出库","零售销售"); //本月零售出库
        BigDecimal monthRetailSaleBack = getBuyAndSaleRetailStatistics("入库", "零售退货",
                monthFirstDay, getNow3(),"入库","仓库退货"); //本月零售退货
        //昨日
        BigDecimal yesterdayBuy = getBuyAndSaleBasicStatistics("入库", "采购",
                1, yesterdayBegin, yesterdayEnd,"其它","收费确认"); //昨日采购入库
        BigDecimal yesterdayBuyBack = getBuyAndSaleBasicStatistics("出库", "采购退货",
                1, yesterdayBegin, yesterdayEnd,"其它","直发采购退货"); //昨日采购退货
        BigDecimal yesterdaySale = getBuyAndSaleBasicStatistics("出库", "销售",
                1, yesterdayBegin, yesterdayEnd,"到货","厂家到货"); //昨日销售出库
        BigDecimal yesterdaySaleBack = getBuyAndSaleBasicStatistics("入库", "销售退货",
                1, yesterdayBegin, yesterdayEnd,"其它","直发销售退货"); //昨日销售退货
        BigDecimal yesterdayRetailSale = getBuyAndSaleRetailStatistics("出库", "零售",
                yesterdayBegin, yesterdayEnd,"出库","零售销售"); //昨日零售出库
        BigDecimal yesterdayRetailSaleBack = getBuyAndSaleRetailStatistics("入库", "零售退货",
                yesterdayBegin, yesterdayEnd,"入库","仓库退货"); //昨日零售退货
        //今年
        BigDecimal yearBuy = getBuyAndSaleBasicStatistics("入库", "采购",
                1, yearBegin, yearEnd,"其它","收费确认"); //今年采购入库
        BigDecimal yearBuyBack = getBuyAndSaleBasicStatistics("出库", "采购退货",
                1, yearBegin, yearEnd,"其它","直发采购退货"); //今年采购退货
        BigDecimal yearSale = getBuyAndSaleBasicStatistics("出库", "销售",
                1, yearBegin, yearEnd,"到货","厂家到货"); //今年销售出库
        BigDecimal yearSaleBack = getBuyAndSaleBasicStatistics("入库", "销售退货",
                1, yearBegin, yearEnd,"其它","直发销售退货"); //今年销售退货
        BigDecimal yearRetailSale = getBuyAndSaleRetailStatistics("出库", "零售",
                yearBegin, yearEnd,"出库","零售销售"); //今年零售出库
        BigDecimal yearRetailSaleBack = getBuyAndSaleRetailStatistics("入库", "零售退货",
                yearBegin, yearEnd,"入库","仓库退货"); //今年零售退货
        map.put("todayBuy", todayBuy.subtract(todayBuyBack));
        map.put("todaySale", todaySale.subtract(todaySaleBack));
        map.put("todayRetailSale", todayRetailSale.subtract(todayRetailSaleBack));
        map.put("monthBuy", monthBuy.subtract(monthBuyBack));
        map.put("monthSale", monthSale.subtract(monthSaleBack));
        map.put("monthRetailSale", monthRetailSale.subtract(monthRetailSaleBack));
        map.put("yesterdayBuy", yesterdayBuy.subtract(yesterdayBuyBack));
        map.put("yesterdaySale", yesterdaySale.subtract(yesterdaySaleBack));
        map.put("yesterdayRetailSale", yesterdayRetailSale.subtract(yesterdayRetailSaleBack));
        map.put("yearBuy", yearBuy.subtract(yearBuyBack));
        map.put("yearSale", yearSale.subtract(yearSaleBack));
        map.put("yearRetailSale", yearRetailSale.subtract(yearRetailSaleBack));
        return map;
    }

    public BigDecimal getBuyAndSaleBasicStatistics(String type, String subType, Integer hasSupplier, String beginTime, String endTime,String type1,String subType1) {
        return depotHeadMapperEx.getBuyAndSaleBasicStatistics(type, subType, hasSupplier, beginTime, endTime,type1,subType1);
    }

    public BigDecimal getBuyAndSaleRetailStatistics(String type, String subType, String beginTime, String endTime,String type1,String subType1) {
        return depotHeadMapperEx.getBuyAndSaleRetailStatistics(type, subType, beginTime, endTime,type1,subType1).abs();
    }

    public DepotHead getDepotHead(String number) throws Exception {
        DepotHead depotHead = new DepotHead();
        try {
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotHead> list = depotHeadMapper.selectByExample(example);
            if (null != list && list.size() > 0) {
                depotHead = list.get(0);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depotHead;
    }

    public List<DepotHead> getDepotHeadByNumberWithSubType(String number, String type, String subType) throws Exception {
        List<DepotHead> list = null;
        try {
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andLinkNumberEqualTo(number).andTypeEqualTo(type).andSubTypeEqualTo(subType).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = depotHeadMapper.selectByExample(example);

        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DepotHeadVo4List> debtList(String organId, String materialParam, String number, String beginTime, String endTime,
                                           String type, String subType, String roleType, String status, String type1, String subType1,
                                           Integer currentPage, Integer pageSize) {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        try {
            String depotIds = depotService.findDepotStrByCurrentUser();
            String[] depotArray = depotIds.split(",");
            String[] creatorArray = getCreatorArray(roleType);
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<DepotHeadVo4List> list = depotHeadMapperEx.debtList(organId, type, subType, creatorArray, status, number, beginTime,
                    endTime, materialParam, depotArray, type1, subType1, currentPage, pageSize);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if (dh.getDeposit() == null) {
                        dh.setDeposit(BigDecimal.ZERO);
                    }
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    dh.setFinishDebt(accountItemService.getEachAmountByBillId(dh.getId()));
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<RequireGoodsVo> requireGoods(String status, Integer pageNum, Integer pageSize) {
        List<RequireGoodsVo> resList = new ArrayList<>();
        try {
            List<RequireGoodsVo> list = depotHeadMapperEx.requireGoods(status, pageNum, pageSize);
            if (null != list) {
                for (RequireGoodsVo vo : list) {
                    vo.setCreateTimeStr(Tools.getCenternTime(vo.getCreateTime()));
                    resList.add(vo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<RequireDetailsVo> requireGoodsDetails(String defaultNumber) {
        List<RequireDetailsVo> resList = new ArrayList<>();
        try {
            List<RequireDetailsVo> list = depotHeadMapperEx.requireGoodsDetails(defaultNumber);
            if (null != list) {
                for (RequireDetailsVo vo : list) {
                    vo.setCreateTimeStr(Tools.getCenternTime(vo.getCreateTime()));
                    resList.add(vo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<FactoryOutLetVo> factoryOutLet(String beginTime,String endTime,String number,String organId, Integer pageNum, Integer pageSize) {
        List<FactoryOutLetVo> resList = new ArrayList<>();
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<FactoryOutLetVo> list = depotHeadMapperEx.factoryOutLet(beginTime,endTime,number,organId, pageNum, pageSize);
            if (null != list) {
                for (FactoryOutLetVo vo : list) {
                    vo.setOperTimeStr(Tools.getCenternTime(vo.getOperTime()));
                    resList.add(vo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<FactoryOutLetDetailVo> factoryOutLetDetails(String headerId) {
        List<FactoryOutLetDetailVo> resList = new ArrayList<>();
        try {
            List<FactoryOutLetDetailVo> list = depotHeadMapperEx.factoryOutLetDetails(headerId);
            if (null != list) {
                for (FactoryOutLetDetailVo vo : list) {
                    vo.setCreateTimeStr(Tools.getCenternTime(vo.getCreateTime()));
                    resList.add(vo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }
//
//    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
//    public void replenishment(String organId,String materialIds,boolean passDirect,String functionId, HttpServletRequest request,Integer day,String depotId) throws Exception {
//        DepotHead depotHead = new DepotHead();
//        depotHead.setId(IdUtils.getUUID());
//        depotHead.setType("其它");
//        depotHead.setSubType("采购订单");
//        String number = sequenceService.buildOnlyNumber();
//        depotHead.setDefaultNumber("CGDD"+number);
//        depotHead.setNumber("CGDD"+number);
//        depotHead.setCreateTime(new Date());
//        depotHead.setOperTime(new Date());
//        depotHead.setOrganId(organId);
//        //判断用户是否已经登录过，登录过不再处理
//        User userInfo=userService.getCurrentUser();
//        depotHead.setCreator(userInfo==null?null:userInfo.getId());
//        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
//        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
//        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
//        depotHead.setPayType("现付");
//        //获取默认结算账户
//        Account accountByDefault = accountService.getAccountByDefault();
//        if(null!=accountByDefault){
//            depotHead.setAccountIdList(accountByDefault.getId());
//        }else {
//            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,"zh".equals(systemConfigService.getLanCode()) ? "未设置默认结算账户" : "No default billing account set");
//        }
//        List<String> materialIdList = StringUtil.strToStringList(materialIds);
//        BigDecimal totalAmount = BigDecimal.ZERO;
//        BigDecimal amount = BigDecimal.ZERO;
//        BigDecimal unitPrice = BigDecimal.ZERO;
//        BigDecimal taxUnitPrice = BigDecimal.ZERO;
//        StringBuilder rows= new StringBuilder("[");
//        for(String materialId : materialIdList){
//            //获取基本单位
//            DepotItemStockWarningCount stockMaterial = depotItemService.findStockByMaterialId(materialId,depotId);
//            if(stockMaterial.getCurrentNumber().compareTo(stockMaterial.getLowSafeStock())<0) {
//                stockMaterial.setLowCritical(stockMaterial.getLowSafeStock().subtract(stockMaterial.getCurrentNumber()));
//            }
//            if(stockMaterial.getCurrentNumber().compareTo(stockMaterial.getHighSafeStock())>0) {
//                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "当前商品"+stockMaterial.getMName()+"库存未达到最低安全库存！" : "The current product "+stockMaterial.getMName()+" inventory has not reached the minimum safety stock!");
//            }
//            MaterialExtend materialExtend = materialExtendService.getInfoByMeId(stockMaterial.getMeId());
//            //获取最近一条采购价
//            BigDecimal recentPurchase = depotItemService.getItemByHeaderIdAndBarcode(materialExtend.getId(),organId,materialId);
//            if (null!=recentPurchase && recentPurchase.compareTo(BigDecimal.ZERO)>0){
//                unitPrice=recentPurchase;
//            }else {
//                unitPrice=materialExtend.getPurchaseDecimal();
//            }
//            amount=unitPrice.multiply(stockMaterial.getLowCritical());
////            if (null != taxRate && taxRate.compareTo(BigDecimal.ZERO)>0){
////                BigDecimal taxMoney = taxRate.multiply(amount);
////                taxLastMoney = taxMoney.add(amount);
////                totalAmount.add(taxLastMoney);
////                rows.append("{\"id\":").append("'"+materialId+"'").append(",\"depotId\":\"\",\"name\":").append("'"+stockMaterial.getMName()+"'").append(",").append("\"standard\":null,\"model\":").append("'"+stockMaterial.getMModel()+"'").append(",\"color\":").append("'"+stockMaterial.getMColor()+"'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'"+stockMaterial.getCurrentNumber()+"'").append(",\"unit\":").append("'"+stockMaterial.getUnitName()+"'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'"+stockMaterial.getLowCritical()+"'").append(",\"unitPrice\":").append("'"+unitPrice+"'").append(",\"allPrice\":").append("'"+amount+"'").append(",\"taxRate\":").append("'"+taxRate+"'").append(",\"taxMoney\":").append("'"+taxMoney+"'").append(",").append("\"taxLastMoney\":").append("'"+taxLastMoney+"'").append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"barCode\":").append("'"+stockMaterial.getBarCode()+"'").append("}");
////            }else {
////                totalAmount.add(amount);
////                rows.append("{\"id\":").append("'"+materialId+"'").append(",\"depotId\":\"\",\"name\":").append("'"+stockMaterial.getMName()+"'").append(",").append("\"standard\":null,\"model\":").append("'"+stockMaterial.getMModel()+"'").append(",\"color\":").append("'"+stockMaterial.getMColor()+"'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'"+stockMaterial.getCurrentNumber()+"'").append(",\"unit\":").append("'"+stockMaterial.getUnitName()+"'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'"+stockMaterial.getLowCritical()+"'").append(",\"unitPrice\":").append("'"+unitPrice+"'").append(",\"allPrice\":").append("'"+amount+"'").append(",\"taxRate\":0,\"taxMoney\":0,").append("\"taxLastMoney\":").append("'"+amount+"'").append(",\"remark\":\"\",\"linkId\":\"\",\"barCode\":").append("'"+stockMaterial.getBarCode()+"'").append("}");
////            }
//            BigDecimal taxMoney = new BigDecimal("0.1").multiply(amount);
//            taxUnitPrice=unitPrice.divide(new BigDecimal("1.1"),2,BigDecimal.ROUND_HALF_UP);
//            totalAmount=totalAmount.add(amount);
//            rows.append("{\"id\":").append("'"+materialId+"'").append(",\"depotId\":\"\",\"name\":").append("'"+stockMaterial.getMName()+"'").append(",").append("\"standard\":null,\"model\":").append("'"+stockMaterial.getMModel()+"'").append(",\"color\":").append("'"+stockMaterial.getMColor()+"'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'"+stockMaterial.getCurrentNumber()+"'").append(",\"unit\":").append("'"+stockMaterial.getUnitName()+"'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'"+stockMaterial.getLowCritical()+"'").append(",\"unitPrice\":").append("'"+unitPrice+"'").append(",\"allPrice\":").append("'"+amount+"'").append(",\"taxRate\":").append("'"+10+"'").append(",\"taxMoney\":").append("'"+taxMoney+"'").append(",").append("\"taxLastMoney\":").append("'"+amount+"'").append(",").append("\"taxUnitPrice\":").append("'"+taxUnitPrice+"'").append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"meId\":").append("'"+stockMaterial.getMeId()+"'").append("}");
//        }
//        rows.append("]");
//        depotHead.setTotalPrice(totalAmount);
//        depotHead.setChangeAmount(BigDecimal.ZERO);
//        depotHead.setDiscount(BigDecimal.ZERO);
//        depotHead.setDiscountMoney(BigDecimal.ZERO);
//        depotHead.setDiscountLastMoney(totalAmount);
//        String lanCode = systemConfigService.getLanCode();
//        depotHead.setRemark("zh".equals(lanCode) ? "智能补货" : "Smart replenishment");
//        Calendar rightNow = Calendar.getInstance();
//        rightNow.setTime(new Date());
//        if (day!=null){
//            rightNow.add(Calendar.DATE, day);
//        }else {
//            rightNow.add(Calendar.DATE, 5);
//        }
//        depotHead.setArrivalTime(rightNow.getTime());
//        try{
//            depotHead.setUploadFlag("0");
//            depotHeadMapper.insertSelective(depotHead);
//        }catch(Exception e){
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
//        //根据单据编号查询单据id
//        DepotHeadExample dhExample = new DepotHeadExample();
//        dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
//        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
//        if(list!=null) {
//            String headId = list.get(0).getId();
//            depotItemService.saveDetials(rows.toString(),headId,"add",request,false);
//        }
//        logService.insertLog("单据",
//                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(depotHead.getNumber()).toString(),
//                StringUtil.getRequest());
//
//
//        audit(depotHead, passDirect, functionId, request);
//    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void replenishment(List<Replenishment> replenishmentList, String organId, boolean passDirect, String functionId, HttpServletRequest request, Integer day) throws Exception {
        DepotHead depotHead = new DepotHead();
        depotHead.setId(IdUtils.getUUID());
        depotHead.setType("其它");
        depotHead.setSubType("采购订单");
        String number = sequenceService.buildOnlyNumber();
        SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
        if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                            : "No system prefix is set");
        }
        if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "未设置税率"
                            : "Untaxed rate");
        }
        //税率
        BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());

        depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"CGDD" + number);
        depotHead.setNumber(systemConfig.getCompanyPostCode()+"CGDD" + number);
        depotHead.setCreateTime(new Date());
        depotHead.setOperTime(new Date());
        depotHead.setOrganId(organId);
        //判断用户是否已经登录过，登录过不再处理
        User userInfo = userService.getCurrentUser();
        depotHead.setCreator(userInfo == null ? null : userInfo.getId());
        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setPayType("现付");
//        //获取默认结算账户
//        Account accountByDefault = accountService.getAccountByDefault();
//        if (null != accountByDefault) {
//            depotHead.setAccountId(accountByDefault.getId());
//        } else {
//            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "未设置默认结算账户" : "No default billing account set");
//        }
//        List<String> materialIdList = StringUtil.strToStringList(materialIds);
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal unitPrice = BigDecimal.ZERO;
        BigDecimal taxUnitPrice = BigDecimal.ZERO;
        StringBuilder rows = new StringBuilder("[");
        for (Replenishment replenishment : replenishmentList) {
            //获取基本单位
            DepotItemStockWarningCount stockMaterial = depotItemService.findStockByMaterialId(replenishment.getId(), replenishment.getDepotId());
            if (stockMaterial.getCurrentNumber().compareTo(stockMaterial.getLowSafeStock()) < 0) {
                stockMaterial.setLowCritical(stockMaterial.getLowSafeStock().subtract(stockMaterial.getCurrentNumber()));
            }
            if (stockMaterial.getCurrentNumber().compareTo(stockMaterial.getHighSafeStock()) > 0) {
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "当前商品" + stockMaterial.getMName() + "库存未达到最低安全库存！" : "The current product " + stockMaterial.getMName() + " inventory has not reached the minimum safety stock!");
            }
            MaterialExtend materialExtend = materialExtendService.getInfoByMeId(stockMaterial.getMeId());
//            //获取最近一条采购价
//            BigDecimal recentPurchase = depotItemService.getItemByHeaderIdAndBarcode(materialExtend.getId(), organId, replenishment.getId());
//            if (null != recentPurchase && recentPurchase.compareTo(BigDecimal.ZERO) > 0) {
//                unitPrice = recentPurchase;
//            } else {
//                unitPrice = materialExtend.getPurchaseDecimal();
//            }
            //固定获取采购价
            unitPrice = materialExtend.getPurchaseDecimal();
            amount = unitPrice.multiply(stockMaterial.getLowCritical());
//            if (null != taxRate && taxRate.compareTo(BigDecimal.ZERO)>0){
//                BigDecimal taxMoney = taxRate.multiply(amount);
//                taxLastMoney = taxMoney.add(amount);
//                totalAmount.add(taxLastMoney);
//                rows.append("{\"id\":").append("'"+materialId+"'").append(",\"depotId\":\"\",\"name\":").append("'"+stockMaterial.getMName()+"'").append(",").append("\"standard\":null,\"model\":").append("'"+stockMaterial.getMModel()+"'").append(",\"color\":").append("'"+stockMaterial.getMColor()+"'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'"+stockMaterial.getCurrentNumber()+"'").append(",\"unit\":").append("'"+stockMaterial.getUnitName()+"'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'"+stockMaterial.getLowCritical()+"'").append(",\"unitPrice\":").append("'"+unitPrice+"'").append(",\"allPrice\":").append("'"+amount+"'").append(",\"taxRate\":").append("'"+taxRate+"'").append(",\"taxMoney\":").append("'"+taxMoney+"'").append(",").append("\"taxLastMoney\":").append("'"+taxLastMoney+"'").append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"barCode\":").append("'"+stockMaterial.getBarCode()+"'").append("}");
//            }else {
//                totalAmount.add(amount);
//                rows.append("{\"id\":").append("'"+materialId+"'").append(",\"depotId\":\"\",\"name\":").append("'"+stockMaterial.getMName()+"'").append(",").append("\"standard\":null,\"model\":").append("'"+stockMaterial.getMModel()+"'").append(",\"color\":").append("'"+stockMaterial.getMColor()+"'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'"+stockMaterial.getCurrentNumber()+"'").append(",\"unit\":").append("'"+stockMaterial.getUnitName()+"'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'"+stockMaterial.getLowCritical()+"'").append(",\"unitPrice\":").append("'"+unitPrice+"'").append(",\"allPrice\":").append("'"+amount+"'").append(",\"taxRate\":0,\"taxMoney\":0,").append("\"taxLastMoney\":").append("'"+amount+"'").append(",\"remark\":\"\",\"linkId\":\"\",\"barCode\":").append("'"+stockMaterial.getBarCode()+"'").append("}");
//            }
            BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
            BigDecimal taxMoney = amount.divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//            BigDecimal taxMoney = taxRate.multiply(amount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
            taxUnitPrice = unitPrice.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
            totalAmount = totalAmount.add(amount);
            rows.append("{\"id\":").append("'" + replenishment.getId() + "'").append(",\"depotId\":\"\",\"name\":").append("''").append(",").append("\"standard\":null,\"model\":").append("'" + stockMaterial.getMModel() + "'").append(",\"color\":").append("'" + stockMaterial.getMColor() + "'").append(",\"materialOther\":\"\",").append("\"stock\":").append("'" + stockMaterial.getCurrentNumber() + "'").append(",\"unit\":").append("'" + stockMaterial.getUnitName() + "'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'" + stockMaterial.getLowCritical() + "'").append(",\"unitPrice\":").append("'" + unitPrice + "'").append(",\"allPrice\":").append("'" + amount + "'").append(",\"taxRate\":").append("'").append(taxRate).append("'").append(",\"taxMoney\":").append("'" + taxMoney + "'").append(",").append("\"taxLastMoney\":").append("'" + amount + "'").append(",").append("\"taxUnitPrice\":").append("'" + taxUnitPrice + "'").append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"meId\":").append("'" + stockMaterial.getMeId() + "'").append("}");
        }
        rows.append("]");
        depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
        depotHead.setChangeAmount(BigDecimal.ZERO);
        depotHead.setDiscount(BigDecimal.ZERO);
        depotHead.setDiscountMoney(BigDecimal.ZERO);
        depotHead.setDiscountLastMoney(totalAmount);
        String lanCode = systemConfigService.getLanCode();
        depotHead.setRemark("zh".equals(lanCode) ? "智能补货" : "Smart replenishment");
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(new Date());
        if (day != null) {
            rightNow.add(Calendar.DATE, day);
        } else {
            rightNow.add(Calendar.DATE, 5);
        }
        depotHead.setArrivalTime(rightNow.getTime());
        try {
            depotHead.setUploadFlag("0");
            depotHeadMapper.insertSelective(depotHead);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        //根据单据编号查询单据id
        DepotHeadExample dhExample = new DepotHeadExample();
        dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
        if (list != null) {
            String headId = list.get(0).getId();
            depotItemService.saveDetials(rows.toString(), headId, "add", request, false);
        }
        logService.insertLog("单据",
                BusinessConstants.LOG_OPERATION_TYPE_ADD + depotHead.getNumber(),
                StringUtil.getRequest());


        audit(depotHead, passDirect, functionId, request);
    }

    public List<DepotHeadVo4List> purchaseAlert(Integer pageNum, Integer pageSize, Integer dayNum) {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();

        try {
            list = depotHeadMapperEx.purchaseAlert(pageNum, pageSize, dayNum);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getArrivalTime() != null) {
                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<DepotHeadVo4List> manufacturerWarning(Integer pageNum, Integer pageSize, Integer dayNum) {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();

        try {
            list = depotHeadMapperEx.manufacturerWarning(pageNum, pageSize, dayNum);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getArrivalTime() != null) {
                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<DepotHeadVo4List> purchaseApplicationAlert(Integer pageNum, Integer pageSize, Integer dayNum) {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();

        try {
            list = depotHeadMapperEx.purchaseApplicationAlert(pageNum, pageSize, dayNum);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getArrivalTime() != null) {
                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resList;
    }

    public List<ShelfLifeWarningVo> shelfLifeWarning(Integer pageNum, Integer pageSize, String tenantId) {
        return depotHeadMapperEx.shelfLifeWarning(pageNum, pageSize, tenantId);
    }


//    public List<DepotHeadVo4List> paymentWarning(Integer pageNum, Integer pageSize, Integer dayNum) {
//        List<DepotHeadVo4List> resList = new ArrayList<>();
//        List<DepotHeadVo4List> list = new ArrayList<>();
//
//        try {
//            list = depotHeadMapperEx.paymentWarning(pageNum, pageSize, dayNum);
//            if (null != list) {
//                for (DepotHeadVo4List dh : list) {
//                    if (dh.getOperTime() != null) {
//                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
//                    }
//                    if (dh.getArrivalTime() != null) {
//                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
//                    }
//                    if (dh.getCreateTime() != null) {
//                        dh.setCreateTimeStr(getCenternTime(dh.getCreateTime()));
//                    }
//                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
//                    resList.add(dh);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return resList;
//    }

    public List<DepotHead> getDepotHeadWithSubType(String subType, List<String> idList) throws Exception {
        List<DepotHead> list = new ArrayList<>();
        try {
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andSubTypeEqualTo(subType).andUploadFlagEqualTo("0").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andAnotherDepotIdIn(idList);
            list = depotHeadMapper.selectByExample(example);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public void checkIsDepotHeadIdList(List<DepotHead> depotHeadList, String subType) throws Exception {
        List<DepotHead> list = new ArrayList<>();
        List<String> idList = new ArrayList<>();
        StringBuilder msg = new StringBuilder();
        try {
            if (null != depotHeadList && depotHeadList.size() > 0) {
                for (DepotHead depotHead : depotHeadList) {
                    idList.add(depotHead.getId());
                }
            }
            DepotHeadExample example = new DepotHeadExample();
            example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andSubTypeEqualTo(subType);

            list = depotHeadMapper.selectByExample(example);
            if (null != list && list.size() > 0) {
                for (DepotHead m : list) {
                    idList.remove(m.getId());
                }
            }
            if (null != depotHeadList && depotHeadList.size() > 0) {
                for (DepotHead depotHead : depotHeadList) {
                    if (idList.contains(depotHead.getId())) {
                        msg.append(depotHead.getNumber()).append(",");
                    }
                }
            }
            if (idList.size() > 0) {
                Msg msgVo = new Msg();
                msgVo.setId(IdUtils.getUUID());
                msgVo.setMsgTitle("新" + subType + "提醒");
                msgVo.setMsgContent("总仓有您新的" + subType + ",单据编号：" + msg.toString() + "请您及时更新");
                msgVo.setCreateTime(new Date());
                msgVo.setType("新" + subType);
                msgVo.setStatus("1");
                msgMapper.insertSelective(msgVo);
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> addRetailOrder(List<AddRetailOrderVo> list, HttpServletRequest request, String equipmentNo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        DepotHead depotHead = new DepotHead();
        StringBuilder rows = new StringBuilder("[");
        try {
            depotHead.setId(IdUtils.getUUID());
            depotHead.setType("出库");
            depotHead.setSubType("零售");
            String number = null;
            number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                map.put("status", 0);
                map.put("msg", "zh".equals(systemConfigService.getLanCode())? "未设置系统前缀"
                        : "No system prefix is set");
                return map;
            }
            depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"LSCK" + number);
            depotHead.setNumber(systemConfig.getCompanyPostCode()+"LSCK" + number);
            depotHead.setOperTime(new Date());
            depotHead.setCustom3(equipmentNo);
//            depotHead.setOrganId(organId);
            //判断用户是否已经登录过，登录过不再处理
            User userInfo = userService.getCurrentUser();
            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
            depotHead.setPayType("现付");
//            depotHead.setAccountId(accountId);
//            Account account = accountService.getAccountByTypeCash();
//            if (account != null) {
//                depotHead.setAccountId(account.getId());
//            }
//            if (StringUtil.isNotEmpty(depotHead.getAccountIdList())) {
//                depotHead.setAccountIdList(depotHead.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", ""));
//            }
//            if (StringUtil.isNotEmpty(depotHead.getAccountMoneyList())) {
//                //校验多账户的结算金额
//                String accountMoneyList = depotHead.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
//                BigDecimal sum = StringUtil.getArrSum(accountMoneyList.split(","));
//                BigDecimal manyAccountSum = sum.abs();
//                if (manyAccountSum.compareTo(depotHead.getChangeAmount().abs()) != 0) {
//                    map.put("status", 0);
//                    map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US);
//                    return map;
////                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
////                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US);
//                }
//                depotHead.setAccountMoneyList(accountMoneyList);
//            }
            BigDecimal totalAmount = BigDecimal.ZERO;

            int i = 1;
            boolean b = true;
            StringBuffer stringBuffer = new StringBuffer();
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                map.put("status", 0);
                map.put("msg","zh".equals(systemConfigService.getLanCode())? "未设置税率" : "Untaxed rate");
                return map;
            }
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());

            for (AddRetailOrderVo addRetailOrderVo : list) {
                List<SingleItemInventoryVo> singleItemInventoryVos = materialService.singleItemInventory(addRetailOrderVo.getGoods_code());
                if (singleItemInventoryVos.size() > 0 && addRetailOrderVo.getNum().compareTo(singleItemInventoryVos.get(0).getInventory()) <= 0) {

                    BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                    BigDecimal taxMoney = addRetailOrderVo.getSubtotal().divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//                    BigDecimal taxMoney = taxRate.multiply(addRetailOrderVo.getSubtotal()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal taxUnitPrice = addRetailOrderVo.getAfterDisPrice().divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                    totalAmount = totalAmount.add(addRetailOrderVo.getSubtotal());
                    rows.append("{\"id\":\"\"")
                            .append(",\"depotId\":")
                            .append("'" + singleItemInventoryVos.get(0).getDepotId() + "'")
                            .append(",").append("\"standard\":null,\"model\":\"\"")
                            .append(",\"color\":\"\"").append(",\"materialOther\":\"\",")
                            .append("\"stock\":").append("'" + singleItemInventoryVos.get(0).getInventory() + "'")
                            .append(",\"unit\":").append("'" + singleItemInventoryVos.get(0).getCommodityUnit() + "'")
                            .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                            .append("\"operNumber\":").append("'" + addRetailOrderVo.getNum() + "'")
                            .append(",\"unitPrice\":").append("'" + addRetailOrderVo.getAfterDisPrice() + "'")
                            .append(",\"allPrice\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"taxLastMoney\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"meId\":").append("'" + addRetailOrderVo.getGoods_code() + "'")
                            .append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"barCode\":")
                            .append("'" + addRetailOrderVo.getGoods_code() + "'")
                            .append(",").append("\"taxUnitPrice\":").append("'" + taxUnitPrice + "'")
                            .append(",").append("\"taxRate\":").append("'" + taxRate + "'")
                            .append(",").append("\"taxMoney\":").append("'" + taxMoney + "'")
                            .append(",").append("\"custom4\":").append("'" + addRetailOrderVo.getCustom4() + "'")
                            .append(",").append("\"priceNote\":").append("'" + addRetailOrderVo.getPriceNote() + "'")
                            .append(",").append("\"discountPrice\":").append("'" + addRetailOrderVo.getRetail_price() + "'")
                            .append(",").append("\"discountAllPrice\":").append("'" + addRetailOrderVo.getDiscountAllPrice() + "'").append("}");

                } else {
                    if ("zh".equals(systemConfigService.getLanCode())) {
                        stringBuffer.append("第");
                        stringBuffer.append(i);
                        stringBuffer.append("个商品");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("库存不足");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    } else {
                        stringBuffer.append(i);
                        stringBuffer.append("st item");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("is out of stock");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    }
                    b = false;
                }
                i++;
            }
            if (!b) {
                map.put("status", 0);
                map.put("msg", stringBuffer.toString());
                return map;
            }
            rows.append("]");
            depotHead.setTotalPrice(totalAmount);
//            depotHead.setChangeAmount(totalAmount);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setBackAmount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            depotHead.setUploadFlag("0");
            depotHeadMapper.insertSelective(depotHead);

        } catch (Exception e) {
            e.printStackTrace();
        }
        depotItemService.saveDetials(rows.toString(), depotHead.getId(), "add", request, false);
//        //更新当前库存
//        depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
        map.put("status", 1);
        map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "订单创建成功" : "Order successfully created");
        map.put("order_no", depotHead.getId());
        map.put("order_number", depotHead.getNumber());
        return map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> addSaleRetailOrder(List<AddRetailOrderVo> list, HttpServletRequest request, String remark, String equipmentNo) throws Exception {

        Map<String, Object> map = new HashMap<>();
//        DepotHeadExample dhExample = new DepotHeadExample();
//        dhExample.createCriteria().andSubTypeEqualTo("零售销售").andCustom3EqualTo(equipmentNo).andStatusEqualTo("0").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
//        List<DepotHead> headList = depotHeadMapper.selectByExample(dhExample);
//        if (headList != null && headList.size() > 0) {
//            map.put("status", 0);
//            if ("zh".equals(systemConfigService.getLanCode())) {
//                map.put("msg", "请等待上一单结算");
//            } else {
//                map.put("msg", "Please wait for the settlement of the previous order");
//            }
//            return map;
//        }
        StringBuilder rows = new StringBuilder("[");
        DepotHead depotHead = new DepotHead();
        try {
            depotHead.setId(IdUtils.getUUID());
            depotHead.setType("出库");
            depotHead.setSubType("零售销售");
            String number = null;
            number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                map.put("status", 0);
                map.put("msg", "zh".equals(systemConfigService.getLanCode())? "未设置系统前缀"
                        : "No system prefix is set");
                return map;
            }
            depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"LSXS" + number);
            depotHead.setNumber(systemConfig.getCompanyPostCode()+"LSXS" + number);
            depotHead.setOperTime(new Date());
            depotHead.setRemark(remark);
            depotHead.setCustom3(equipmentNo);
//            depotHead.setOrganId(organId);
            //判断用户是否已经登录过，登录过不再处理
            User userInfo = userService.getCurrentUser();
//            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            depotHead.setSalesMan(userInfo == null ? null : userInfo.getId());
            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.PURCHASE_STATUS_UN_AUDIT);
            depotHead.setPayType("现付");
            BigDecimal totalAmount = BigDecimal.ZERO;
            int i = 1;
            boolean b = true;
            StringBuffer stringBuffer = new StringBuffer();
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                map.put("status", 0);
                map.put("msg","zh".equals(systemConfigService.getLanCode())? "未设置税率" : "Untaxed rate");
                return map;
            }
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());
            for (AddRetailOrderVo addRetailOrderVo : list) {
                List<SingleItemInventoryVo> singleItemInventoryVos = materialService.singleItemInventory(addRetailOrderVo.getId());
                if (singleItemInventoryVos.size() > 0 && addRetailOrderVo.getNum().compareTo(singleItemInventoryVos.get(0).getInventory()) <= 0) {

                    BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                    BigDecimal taxMoney = addRetailOrderVo.getSubtotal().divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);


//                    BigDecimal taxMoney = taxRate.multiply(addRetailOrderVo.getSubtotal()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal taxUnitPrice = addRetailOrderVo.getAfterDisPrice().divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                    totalAmount = totalAmount.add(addRetailOrderVo.getSubtotal());
                    rows.append("{\"id\":\"\"").append(",\"meId\":").append("'" + addRetailOrderVo.getId() + "'")
                            .append(",\"depotId\":").append("'" + singleItemInventoryVos.get(0).getDepotId() + "'")
                            .append(",")
                            .append("\"standard\":null,\"model\":\"\"").append(",\"color\":\"\"")
                            .append(",\"materialOther\":\"\",").append("\"stock\":")
                            .append("'" + singleItemInventoryVos.get(0).getInventory() + "'")
                            .append(",\"unit\":").append("'" + singleItemInventoryVos.get(0).getCommodityUnit() + "'")
                            .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                            .append("\"operNumber\":").append("'" + addRetailOrderVo.getNum() + "'")
                            .append(",\"unitPrice\":").append("'" + addRetailOrderVo.getAfterDisPrice() + "'")
                            .append(",\"allPrice\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"taxLastMoney\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"barCode\":")
                            .append("'" + addRetailOrderVo.getGoods_code() + "'")
                            .append(",").append("\"taxUnitPrice\":").append("'" + taxUnitPrice + "'")
                            .append(",").append("\"taxRate\":").append("'" + taxRate + "'")
                            .append(",").append("\"taxMoney\":").append("'" + taxMoney + "'")
                            .append(",").append("\"custom4\":").append("'" + addRetailOrderVo.getCustom4() + "'")
                            .append(",").append("\"priceNote\":").append("'" + addRetailOrderVo.getPriceNote() + "'")
                            .append(",").append("\"discountPrice\":").append("'" + addRetailOrderVo.getRetail_price() + "'")
                            .append(",").append("\"discountAllPrice\":").append("'" + addRetailOrderVo.getDiscountAllPrice() + "'")
                            .append("}");
                } else {
                    if ("zh".equals(systemConfigService.getLanCode())) {
                        stringBuffer.append("第");
                        stringBuffer.append(i);
                        stringBuffer.append("个商品");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("库存不足");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    } else {
                        stringBuffer.append(i);
                        stringBuffer.append("st item");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("is out of stock");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    }
                    b = false;
                }
                i++;
            }
            if (!b) {
                map.put("status", 0);
                map.put("msg", stringBuffer.toString());
                return map;
            }
            rows.append("]");
            depotHead.setTotalPrice(totalAmount);
            depotHead.setChangeAmount(BigDecimal.ZERO);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setBackAmount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            depotHead.setUploadFlag("0");
            depotHeadMapper.insertSelective(depotHead);

        } catch (Exception e) {
            e.printStackTrace();
        }
        depotItemService.saveDetials(rows.toString(), depotHead.getId(), "add", request, false);
        //更新当前库存
        depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
        map.put("status", 1);
        map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "订单创建成功" : "Order successfully created");
        map.put("order_no", depotHead.getId());
        map.put("order_number", depotHead.getNumber());
        return map;
    }

    public List<Map<String, Object>> getShoppingRunningWater(String beginTime, String endTime,
                                                             List<String> depotList, Integer offset, Integer rows, String orderNumber) throws Exception {
        List<DepotHeadWithPos> list = null;
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            list = depotHeadMapperEx.getShoppingRunningWater(beginTime, endTime, depotList, orderNumber, offset, rows);
            Map<String, String> accountMap = accountService.getAccountMap();
            if (null != list && list.size() > 0) {
                for (DepotHeadWithPos dep : list) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", dep.getId());
                    map.put("order_no", dep.getNumber());
                    map.put("add_time", dep.getOperTime());
                    map.put("settlement_type", 1);
                    map.put("order_type", dep.getOrderType());
                    map.put("all_money", dep.getTotalPrice());
                    map.put("payType", dep.getPayType());
                    map.put("pay_status", dep.getStatus());
                    map.put("pay_money", dep.getChangeAmount());
                    map.put("vip_class", "散客");
                    map.put("amount_received", dep.getChangeAmount());
                    map.put("give_change", dep.getBackAmount());
                    map.put("goods_info", dep.getMaterialList());
                    if (accountMap != null && StringUtil.isNotEmpty(dep.getAccountIdList()) && StringUtil.isNotEmpty(dep.getAccountMoneyList())) {
                        String accountStr = accountService.getPosAccountStrByIdAndMoney(accountMap, dep.getAccountIdList(), dep.getAccountMoneyList());
                        map.put("accountName", accountStr);
                    }
                    if (StringUtil.isNotEmpty(dep.getAccount())){
                        String accountStr= dep.getAccount()+"(" + dep.getChangeAmount().stripTrailingZeros().toPlainString()+ ") ";
                        map.put("accountName", accountStr);
                    }
                    User user = userService.getUser(dep.getSalesMan());
                    if (null !=user){
                        map.put("salesManStr", user.getLoginName());
                    }

                    mapList.add(map);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return mapList;
    }

    public int getShoppingRunningWaterCount(String beginTime, String endTime, List<String> depotList, String orderNumber) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.getShoppingRunningWaterCount(beginTime, endTime, depotList, orderNumber);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public Map<String, Object> searchOrder_v1(String order_no) throws Exception {
        DepotHeadWithPos dep = null;
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        dep = depotHeadMapperEx.searchOrder_v1(order_no);
        if (null != dep) {
            map.put("status", 1);
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "查询成功" : "search successful");
            map.put("finish_time", "123213");
            dataMap.put("order_no", dep.getNumber());
            dataMap.put("amount_received", dep.getChangeAmount().toString());
            List<PosMaterial> materialList = dep.getMaterialList();
            if (null != materialList) {
                for (PosMaterial material : materialList) {
                    Map<String, Object> goodsInfo = new HashMap<String, Object>();
                    goodsInfo.put("goods_type", material.getGoods_type());
                    if (StringUtils.isEmpty(material.getPricing_method())) {
                        goodsInfo.put("pricing_method", "1");
                    } else {
                        goodsInfo.put("pricing_method", material.getPricing_method() == null || material.getPricing_method().equals(0) ? "1" : "2");
                    }
                    goodsInfo.put("original_price", material.getOriginal_price());
                    goodsInfo.put("price", material.getPrice());
                    goodsInfo.put("goods_id", material.getMaterialId());
                    goodsInfo.put("goods_code", material.getGoods_code());
                    goodsInfo.put("num", material.getNum());
                    goodsInfo.put("all_money", material.getAll_money());
                    goodsInfo.put("goods_name", material.getGoods_name());
                    Unit unitInfo = materialService.findUnit(material.getMaterialId());
                    Map<String, Object> refund = depotItemService.getFinishPosNumber(material.getMaterialExtendId(), material.getId(), dep.getId(), unitInfo, material.getMaterialUnit(), "零售退货");
                    BigDecimal count = (BigDecimal) refund.get("basicNumber");
                    goodsInfo.put("refund_num", count); //已经退货数量
                    goodsInfo.put("attribute_state", "1");  //规格状态
                    goodsInfo.put("sku_json_info", "[]");
                    goodsInfo.put("integral_dis_money", "0.00");
                    goodsInfo.put("goods_img", attachmentService.getAttachmentById(material.getMaterialId()));
                    goodsInfo.put("goods_count", material.getNum());
                    if (count == null) {
                        goodsInfo.put("now_num", material.getNum()); //可退货数量
                    } else {
                        goodsInfo.put("now_num", material.getNum().subtract(count)); //可退货数量
                    }
                    goodsInfo.put("refund_money", refund.get("allPrice")); //已退货金额
                    result.add(goodsInfo);
                }
            }
            dataMap.put("goods_info", result);
            map.put("data", dataMap);
        } else {
            map.put("status", 0);
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "订单不存在" : "order does not exist");
        }
        return map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> updateRetailOrder(String order_no, BigDecimal amount_received, BigDecimal all_money, HttpServletRequest request, String accountMoneyList, String accountIdList,
                                   String accountId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(order_no);
        depotHead.setChangeAmount(amount_received);
        depotHead.setTotalPrice(all_money);
        depotHead.setBackAmount(amount_received.subtract(all_money));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_AUDIT);
        depotHead.setUploadFlag("0");

        depotHead.setAccountId(accountId);
//            Account account = accountService.getAccountByTypeCash();
//            if (account != null) {
//                depotHead.setAccountId(account.getId());
//            }
        if (StringUtil.isNotEmpty(accountIdList)) {
            depotHead.setAccountIdList(accountIdList.replace("[", "").replace("]", "").replaceAll("\"", ""));
        }
        if (StringUtil.isNotEmpty(accountMoneyList)) {
            //校验多账户的结算金额
            String newAccountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replaceAll("\"", "");
            BigDecimal sum = StringUtil.getArrSum(newAccountMoneyList.split(","));
            BigDecimal manyAccountSum = sum.abs();
            if (manyAccountSum.compareTo(depotHead.getTotalPrice().abs()) != 0) {
                map.put("status", 0);
                map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US);
                return map;
//                    throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_CODE,
//                            "zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_MANY_ACCOUNT_FAILED_MSG_US);
            }
            depotHead.setAccountMoneyList(accountMoneyList);
        }

        depotHeadMapper.updateByPrimaryKeySelective(depotHead);
        String userId = userService.getUserId(request);
        RetailRecordEx recordEx = retailRecordMapperEx.getByIdWithStartTime(userId);
        if (recordEx.getRmbpay() != null) {
            recordEx.setRmbpay(recordEx.getRmbpay().add(amount_received));
        } else {
            recordEx.setRmbpay(BigDecimal.ZERO.add(amount_received));
        }
        recordEx.setUploadFlag("0");
        retailRecordMapper.updateByPrimaryKeySelective(recordEx);
        //更新当前库存
        depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
        map.put("status", 1);
        map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "付款成功" : "successful payment");
        map.put("all_money", all_money);
        return  map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Map<String, Object> addSearchOrder(JSONObject jsonObject, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        DepotHeadExample example = new DepotHeadExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andNumberEqualTo(jsonObject.getString("order_no"));
        List<DepotHead> depotHeadList = depotHeadMapper.selectByExample(example);
        if (depotHeadList.size() <= 0) {
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "未查询到该订单" : "The order was not found");
            map.put("status", 0);
            return map;
        }
        if (StringUtils.isEmpty(jsonObject.getString("goods_info"))) {
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "退款码不能为空" : "Refund code cannot be empty");
            map.put("status", 0);
            return map;
        }
        List<Map<String, Object>> goodsInfoList = new ArrayList<>();
        DepotHead head = depotHeadList.get(0);
        List<AddSearchOrderVo> retailOrderVoList = JSONObject.parseArray(jsonObject.getString("goods_info"), AddSearchOrderVo.class);
        BigDecimal totalAmount = BigDecimal.ZERO;
        StringBuilder rows = new StringBuilder("[");
        for (AddSearchOrderVo addSearchOrderVo : retailOrderVoList) {
            Map<String, Object> goodsInfo = new HashMap<String, Object>();
            DepotItemExample itemExample = new DepotItemExample();
            itemExample.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andHeaderIdEqualTo(head.getId());
            List<DepotItem> depotItemList = depotItemMapper.selectByExample(itemExample);
            if (depotItemList.size() > 0) {
                totalAmount = totalAmount.add(addSearchOrderVo.getOriginal_price().multiply(addSearchOrderVo.getGoods_count()));
                rows.append("{\"id\":\"\"").append(",\"depotId\":").append("'" + depotItemList.get(0).getDepotId() + "'").append(",\"name\":").append("''").append(",").append("\"standard\":null,\"model\":\"\"").append(",\"color\":\"\"").append(",\"materialOther\":\"\",").append("\"stock\":\"\"").append(",\"unit\":").append("'" + depotItemList.get(0).getMaterialUnit() + "'").append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",").append("\"operNumber\":").append("'" + addSearchOrderVo.getGoods_count() + "'").append(",\"unitPrice\":").append("'" + addSearchOrderVo.getOriginal_price() + "'").append(",\"allPrice\":").append("'" + addSearchOrderVo.getOriginal_price().multiply(addSearchOrderVo.getGoods_count()) + "'").append(",\"taxRate\":\"\"").append(",\"taxMoney\":\"\"").append(",").append("\"taxLastMoney\":\"\"").append(",\"remark\":\"\",\"linkId\":").append("'" + depotItemList.get(0).getId() + "'").append(",\"orderNum\":1,\"barCode\":").append("'" + addSearchOrderVo.getGoods_code() + "'").append("}");
                goodsInfo.put("num", addSearchOrderVo.getGoods_count());
                goodsInfo.put("all_money", addSearchOrderVo.getOriginal_price().multiply(addSearchOrderVo.getGoods_count()));
                goodsInfo.put("before_all_money", addSearchOrderVo.getOriginal_price().multiply(addSearchOrderVo.getGoods_count()));
                goodsInfo.put("price", addSearchOrderVo.getOriginal_price());
                goodsInfo.put("pricing_method", addSearchOrderVo.getPricing_method());
                goodsInfo.put("goods_name", addSearchOrderVo.getGoods_name());
            } else {
                map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "获取退款详情失败" : "Failed to get refund details");
                map.put("status", 0);
                return map;
            }
            goodsInfoList.add(goodsInfo);
        }
        rows.append("]");
        DepotHead depotHead = new DepotHead();
        depotHead.setId(IdUtils.getUUID());
        depotHead.setType("入库");
        depotHead.setSubType("零售退货");
        String number = sequenceService.buildOnlyNumber();
        SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
        if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
            map.put("status", 0);
            map.put("msg", "zh".equals(systemConfigService.getLanCode())? "未设置系统前缀"
                    : "No system prefix is set");
            return map;
        }
        depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"LSTH" + number);
        depotHead.setNumber(systemConfig.getCompanyPostCode()+"LSTH" + number);
        depotHead.setCreateTime(new Date());
        depotHead.setOperTime(new Date());
        //判断用户是否已经登录过，登录过不再处理
        User userInfo = userService.getCurrentUser();
        depotHead.setCreator(userInfo == null ? null : userInfo.getId());
        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setPayType("现付");
        depotHead.setTotalPrice(totalAmount.negate());
        depotHead.setChangeAmount(totalAmount.negate());
        depotHead.setDiscount(BigDecimal.ZERO);
        depotHead.setBackAmount(BigDecimal.ZERO);
        depotHead.setDiscountMoney(BigDecimal.ZERO);
//        depotHead.setDiscountLastMoney(totalAmount);
        depotHead.setLinkNumber(head.getNumber());
        depotHead.setUploadFlag("0");
        depotHeadMapper.insertSelective(depotHead);
        depotItemService.saveDetials(rows.toString(), depotHead.getId(), "add", request, false);
        RetailRecordEx recordEx = retailRecordMapperEx.getByIdWithStartTime(userInfo.getId());
        if (recordEx.getRmbpay() != null) {
            recordEx.setRmbpay(recordEx.getRmbpay().subtract(totalAmount));
        } else {
            recordEx.setRmbpay(BigDecimal.ZERO.subtract(totalAmount));
        }
        recordEx.setUploadFlag("0");
        retailRecordMapper.updateByPrimaryKeySelective(recordEx);
        //退款数据
        Map<String, Object> data = new HashMap<String, Object>();
        List<Map<String, Object>> refundList = new ArrayList<>();
        Map<String, Object> refund = new HashMap<String, Object>();
        data.put("all_money", totalAmount);
        data.put("end_time", System.currentTimeMillis() / 1000);
        data.put("order_no", depotHead.getNumber());
        data.put("pay_coupon_fee", 0);
        data.put("job_num", userInfo == null ? null : userInfo.getLoginName());
        data.put("store_name", userService.getUser(userInfo.getTenantId()).getLoginName());
        data.put("refund_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        refund.put("name", "现金");
        refund.put("type", "3");
        refund.put("money", totalAmount);
        refundList.add(refund);
        data.put("refund_list", refundList);
        data.put("goods_info", goodsInfoList);


        //退款成功
        Map<String, Object> refundRes = new HashMap<String, Object>();
        map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "退款原单更新成功，新单据添加成功" : "The original refund order has been updated successfully, and the new order has been added successfully.");
        map.put("status", 1);
        map.put("data", data);
        refundRes.put("msg", "退款成功");
        refundRes.put("status", 1);
        map.put("refundRes", refundRes);
        return map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public Object uploadOffpayOrder(JSONObject jsonObject, HttpServletRequest request) {
        JSONObject order_info = jsonObject.getJSONObject("order_info");
        List<AddRetailOrderVo> goodsList = JSONObject.parseArray(order_info.getJSONArray("goodsList").toJSONString(), AddRetailOrderVo.class);
        Map<String, Object> map = new HashMap<>();
        DepotHead depotHead = new DepotHead();
        try {
            depotHead.setId(IdUtils.getUUID());
            depotHead.setType("出库");
            depotHead.setSubType("零售");
            String number = null;
            number = sequenceService.buildOnlyNumber();
//            depotHead.setDefaultNumber(order_info.getString("order_number"));
//            depotHead.setNumber(order_info.getString("order_number"));
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                map.put("status", 0);
                map.put("msg", "zh".equals(systemConfigService.getLanCode())? "未设置系统前缀"
                        : "No system prefix is set");
                return map;
            }
            depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"LSCK" + number);
            depotHead.setNumber(systemConfig.getCompanyPostCode()+"LSCK" + number);
            Timestamp add_time = new Timestamp(order_info.getLongValue("add_time") * 1000);
            depotHead.setOperTime(add_time);
            depotHead.setCreateTime(add_time);
//            depotHead.setOrganId(organId);
            //判断用户是否已经登录过，登录过不再处理
            User userInfo = userService.getCurrentUser();
            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            Account account = accountService.getAccountByTypeCash();
            if (account != null) {
                depotHead.setAccountId(account.getId());
            }
//            depotHead.setCreator(order_info.getString("cashier_id"));
//            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_AUDIT);
            depotHead.setPayType("现付");
            depotHead.setRemark("Off-line document");
            BigDecimal totalAmount = BigDecimal.ZERO;
            StringBuilder rows = new StringBuilder("[");
            int i = 1;
            boolean b = true;
            StringBuffer stringBuffer = new StringBuffer();
            for (AddRetailOrderVo addRetailOrderVo : goodsList) {
                List<SingleItemInventoryVo> singleItemInventoryVos = materialService.singleItemInventory(addRetailOrderVo.getGoods_code());
                if (singleItemInventoryVos.size() > 0 && addRetailOrderVo.getNum().compareTo(singleItemInventoryVos.get(0).getInventory()) == -1) {
                    totalAmount = totalAmount.add(addRetailOrderVo.getSubtotal());
                    rows.append("{\"id\":\"\"")
                            .append(",\"depotId\":")
                            .append("'" + singleItemInventoryVos.get(0).getDepotId() + "'")
                            .append(",").append("\"standard\":null,\"model\":\"\"")
                            .append(",\"color\":\"\"").append(",\"materialOther\":\"\",")
                            .append("\"stock\":").append("'" + singleItemInventoryVos.get(0).getInventory() + "'")
                            .append(",\"unit\":").append("'" + singleItemInventoryVos.get(0).getCommodityUnit() + "'")
                            .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                            .append("\"operNumber\":").append("'" + addRetailOrderVo.getNum() + "'")
                            .append(",\"unitPrice\":").append("'" + addRetailOrderVo.getAfterDisPrice() + "'")
                            .append(",\"allPrice\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"taxLastMoney\":").append("'" + addRetailOrderVo.getSubtotal() + "'")
                            .append(",\"meId\":").append("'" + addRetailOrderVo.getGoods_code() + "'")
                            .append(",\"taxRate\":\"\"").append(",\"taxMoney\":\"\"").append(",")
                            .append("\"taxLastMoney\":\"\"").append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"barCode\":")
                            .append("'" + addRetailOrderVo.getGoods_code() + "'")
                            .append(",").append("\"custom4\":").append("'" + addRetailOrderVo.getCustom4() + "'")
                            .append(",").append("\"priceNote\":").append("'" + addRetailOrderVo.getPriceNote() + "'")
                            .append(",").append("\"discountPrice\":").append("'" + addRetailOrderVo.getRetail_price() + "'")
                            .append(",").append("\"discountAllPrice\":").append("'" + addRetailOrderVo.getDiscountAllPrice() + "'").append("}");
                } else {
                    if ("zh".equals(systemConfigService.getLanCode())) {
                        stringBuffer.append("第");
                        stringBuffer.append(i);
                        stringBuffer.append("个商品");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("库存不足");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    } else {
                        stringBuffer.append(i);
                        stringBuffer.append("st item");
                        stringBuffer.append(addRetailOrderVo.getGoods_name());
                        stringBuffer.append("is out of stock");
                        stringBuffer.append(addRetailOrderVo.getNum());
                    }
                    b = false;
                }
                i++;
            }
            if (!b) {
                map.put("status", 0);
                map.put("msg", stringBuffer.toString());
                return map;
            }
            rows.append("]");
            depotHead.setTotalPrice(totalAmount);
            depotHead.setChangeAmount(totalAmount);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setBackAmount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            depotHead.setUploadFlag("0");
            depotHeadMapper.insertSelective(depotHead);
            depotItemService.saveDetials(rows.toString(), depotHead.getId(), "add", request, false);
            RetailRecordEx recordEx = retailRecordMapperEx.getByIdWithStartTime(userInfo.getId());
            if (recordEx.getRmbpay() != null) {
                recordEx.setRmbpay(recordEx.getRmbpay().subtract(totalAmount));
            } else {
                recordEx.setRmbpay(BigDecimal.ZERO.subtract(totalAmount));
            }
            recordEx.setUploadFlag("0");
            retailRecordMapper.updateByPrimaryKeySelective(recordEx);

            //更新当前库存
            depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);

            map.put("status", 1);
            map.put("msg", "zh".equals(systemConfigService.getLanCode()) ? "订单创建成功" : "Order successfully created");
            map.put("order_no", depotHead.getId());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int issuePurchase(DepotHead node, String rows, boolean passDirect, String functionId, HttpServletRequest request) throws Exception {
        JSONArray jsonArray = JSONArray.parseArray(rows);
        Map<String, List<JSONObject>> map = new HashMap<String, List<JSONObject>>();
        String tempIdStr = "";
        List<JSONObject> list = null;
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            tempIdStr = jsonObject.getString("organId");
            if (map.containsKey(tempIdStr)) {
                list = map.get(tempIdStr);
                list.add(jsonObject);
            } else {
                list = new ArrayList<JSONObject>();
                list.add(jsonObject);
                map.put(tempIdStr, list);
            }
        }

        for (Map.Entry<String, List<JSONObject>> entry : map.entrySet()) {
            List<JSONObject> jsonObjectList = entry.getValue();
            DepotHead depotHead = new DepotHead();
            depotHead.setId(IdUtils.getUUID());
            depotHead.setType("其它");
            depotHead.setSubType("下达采购");
            String number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                                : "No system prefix is set");
            }
            depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"XDCG" + number);
            depotHead.setNumber(systemConfig.getCompanyPostCode()+"XDCG" + number);
            depotHead.setCreateTime(new Date());
            depotHead.setOperTime(new Date());
            depotHead.setOrganId(entry.getKey());
            //判断用户是否已经登录过，登录过不再处理
            User userInfo = userService.getCurrentUser();
            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setPayType("现付");
//            //获取默认结算账户
//            Account accountByDefault = accountService.getAccountByDefault();
//            if (null != accountByDefault) {
//                depotHead.setAccountId(accountByDefault.getId());
//            } else {
//                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "zh".equals(systemConfigService.getLanCode()) ? "未设置默认结算账户" : "No default billing account set");
//            }
            //获取最近一条采购价
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (JSONObject object : jsonObjectList) {
                BigDecimal taxLastMoney = object.getBigDecimal("taxLastMoney");
                totalAmount = totalAmount.add(taxLastMoney);
            }
            depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
            depotHead.setChangeAmount(BigDecimal.ZERO);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            depotHead.setArrivalTime(node.getArrivalTime());
            depotHead.setLinkNumber(node.getNumber());
            depotHead.setFreightStatus("0");
            depotHead.setQuotationStatus("0");
            try {
                depotHead.setUploadFlag("0");
                depotHeadMapper.insertSelective(depotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }
            depotItemService.saveDetials(entry.getValue().toString(), depotHead.getId(), "add", request, true);

            audit(depotHead, passDirect, functionId, request);
        }
        return map.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void procurementAcceptance(DepotHead depotHead, List<DepotItemVo4WithInfoEx> depotItems, boolean passDirect, String functionId, HttpServletRequest request, Map<String, String> depotIdMap, Map<String, Map<String, Object>> linkIdMap) throws Exception {
        String linkNumber = depotHead.getNumber();
        depotHead.setId(IdUtils.getUUID());
        depotHead.setType("其它");
        depotHead.setSubType("收费确认");
        String number = sequenceService.buildOnlyNumber();
        SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
        if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
            throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                    "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                            : "No system prefix is set");
        }
        depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"SFQR" + number);
        depotHead.setNumber(systemConfig.getCompanyPostCode()+"SFQR" + number);
        depotHead.setCreateTime(new Date());
        depotHead.setOperTime(new Date());
        //判断用户是否已经登录过，登录过不再处理
        User userInfo = userService.getCurrentUser();
        depotHead.setCreator(userInfo == null ? null : userInfo.getId());
        depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
        depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
        depotHead.setLinkNumber(linkNumber);
        depotHead.setOtherMoney(BigDecimal.ZERO);

        Set<String> existsSets = linkIdMap.keySet();
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal taxUnitPrice = BigDecimal.ZERO;
        List<DepotItemVo4WithInfoEx> inLinkIdDepotItemList= new ArrayList<>();
        for (DepotItemVo4WithInfoEx depotItem : depotItems) {
            if (existsSets.contains(depotItem.getLinkId())){
                Map<String, Object> stringObjectMap = linkIdMap.get(depotItem.getLinkId());
                depotItem.setDepotId(depotIdMap.get(depotItem.getMaterialExtendId()));
                depotItem.setUnit(depotItem.getMaterialUnit());
                if (stringObjectMap !=null){
                    if (StringUtil.isExist(stringObjectMap.get("differNumber"))) {
                        depotItem.setDifferNumber((BigDecimal)stringObjectMap.get("differNumber"));
                    }
                    if (StringUtil.isExist(stringObjectMap.get("custom11"))) {
                        depotItem.setCustom11((Integer)stringObjectMap.get("custom11"));
                    }
                    BigDecimal operNumber = (BigDecimal) stringObjectMap.get("operNumber");
                    BigDecimal unitPrice = depotItem.getUnitPrice();

                    amount = unitPrice.multiply(operNumber);
                    BigDecimal taxMoney = new BigDecimal("0.1").multiply(amount);
                    taxUnitPrice = unitPrice.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                    totalAmount = totalAmount.add(amount);

                    BigDecimal basicNumber = (BigDecimal) stringObjectMap.get("basicNumber");
                    depotItem.setOperNumber(operNumber);
                    depotItem.setBasicNumber(basicNumber);
                    depotItem.setAllPrice(amount);
                    depotItem.setTaxLastMoney(amount);
                    depotItem.setTaxMoney(taxMoney);
                    depotItem.setTaxUnitPrice(taxUnitPrice);
                }
                inLinkIdDepotItemList.add(depotItem);
            }
        }
        depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
        depotHead.setChangeAmount(BigDecimal.ZERO);
        depotHead.setDiscount(BigDecimal.ZERO);
        depotHead.setDiscountMoney(BigDecimal.ZERO);
        depotHead.setDiscountLastMoney(totalAmount);
        //单据遗留租户 清空
        depotHead.setTenantId(null);
        if (inLinkIdDepotItemList.size() > 0){
            try {
                depotHead.setUploadFlag("0");
                depotHeadMapper.insertSelective(depotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }

            String depotItemString = JSONObject.toJSONString(inLinkIdDepotItemList);
            depotItemService.saveDetials(depotItemString, depotHead.getId(), "add", request, true);
            audit(depotHead, passDirect, functionId, request);
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void purchaseReturn(DepotHead depotHead, List<DepotItemVo4WithInfoEx> depotItems, boolean passDirect, String subType, HttpServletRequest request) throws Exception {
        //判断用户是否已经登录过，登录过不再处理
        User userInfo = userService.getCurrentUser();
        String functionName = null;
        switch (subType) {
            case "采购":
                functionName="验收入库";
                break;
            case "厂家到货":
                functionName="厂家到货验收单";
                break;
            case "收费确认":
                functionName="下达采购验收单";
                break;
            case "验收":
                functionName="验收单";
                break;
        }
        Function function = functionService.findByName(functionName);
        String linkNumber = depotHead.getNumber();
        List<DepotItemVo4WithInfoEx> breakage = depotItems.stream().collect(Collectors.groupingBy(DepotItemVo4WithInfoEx::getCustom11)).get(1);
        if (null != breakage && breakage.size() > 0) {
            depotHead.setId(IdUtils.getUUID());
            String number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                                : "No system prefix is set");
            }
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置税率"
                                : "Untaxed rate");
            }
            //税率
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());
            switch (subType) {
                case "采购":
                    depotHead.setType("出库");
                    depotHead.setSubType("采购退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"CGTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"CGTH" + number);
                    break;
                case "厂家到货":
                    depotHead.setType("其它");
                    depotHead.setSubType("直发销售退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"ZFXXTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"ZFXXTH" + number);
                    break;
                case "收费确认":
                    depotHead.setType("其它");
                    depotHead.setSubType("直发采购退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"ZFCGTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"ZFCGTH" + number);
                    break;
                case "验收":
                    depotHead.setType("其它");
                    depotHead.setSubType("验收退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"YSTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"YSTH" + number);
                    break;
            }

            depotHead.setOrganId(depotHead.getOrganId());
            depotHead.setCreateTime(new Date());
            depotHead.setOperTime(new Date());
            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setLinkNumber(linkNumber);
            depotHead.setOtherMoney(BigDecimal.ZERO);
            //单据遗留租户 清空
            depotHead.setTenantId(null);
            StringBuilder rows = new StringBuilder("[");
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal taxUnitPrice = BigDecimal.ZERO;
            for (DepotItemVo4WithInfoEx infoEx : breakage) {
                //单价
                BigDecimal purchaseDecimal =BigDecimal.ZERO;
                BigDecimal discountPrice =BigDecimal.ZERO;
                if ("验收".equals(subType)){
                    if(null !=infoEx.getPurchaseDecimal() && infoEx.getPurchaseDecimal().compareTo(BigDecimal.ZERO)>0){
                        purchaseDecimal = infoEx.getPurchaseDecimal();
                    }else {
                        throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_PURCHASE_NULL_CODE,
                                String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_PURCHASE_NULL_MSG : ExceptionConstants.DEPOT_HEAD_PURCHASE_NULL_MSG_US,infoEx.getMName()));
                    }
                }else {
                    purchaseDecimal = infoEx.getUnitPrice();
                    discountPrice = infoEx.getDiscountPrice();
                }
                //数量
                BigDecimal differNumber = infoEx.getDifferNumber();
                amount = purchaseDecimal.multiply(differNumber);

                BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                BigDecimal taxMoney = amount.divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//                BigDecimal taxMoney = taxRate.multiply(amount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                taxUnitPrice = purchaseDecimal.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(amount);
                BigDecimal discountAllPrice = BigDecimal.ZERO;
                if (discountPrice != null && discountPrice.compareTo(BigDecimal.ZERO)>0){
                    discountAllPrice = discountPrice.subtract(purchaseDecimal).multiply(differNumber);
                }

                rows.append("{\"id\":").append("'").append(IdUtils.getUUID()).append("'")
                        .append(",\"depotId\":").append("'").append(infoEx.getDepotId()).append("'")
                        .append(",").append("\"standard\":null,\"model\":").append("'").append(infoEx.getMModel()).append("'")
                        .append(",\"color\":").append("'").append(infoEx.getMColor()).append("'")
                        .append(",\"unit\":").append("'").append(infoEx.getMaterialUnit()).append("'")
                        .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                        .append("\"operNumber\":").append("'").append(differNumber).append("'")
                        .append(",\"unitPrice\":").append("'").append(purchaseDecimal).append("'")
                        .append(",\"allPrice\":").append("'").append(amount).append("'")
                        .append(",\"taxRate\":").append("'").append(taxRate).append("'")
                        .append(",\"custom5\":").append("'").append(infoEx.getCustom5()).append("'")
                        .append(",\"taxMoney\":").append("'").append(taxMoney).append("'")
                        .append(",").append("\"taxLastMoney\":").append("'").append(amount).append("'")
                        .append(",").append("\"taxUnitPrice\":").append("'").append(taxUnitPrice).append("'")
                        .append(",").append("\"discountAllPrice\":").append("'").append(discountAllPrice).append("'")
                        .append(",").append("\"discountPrice\":").append("'").append(discountPrice).append("'")
                        .append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"meId\":").append("'").append(infoEx.getMeId()).append("'").append("}");

            }
            rows.append("]");
            depotHead.setChangeAmount(BigDecimal.ZERO);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            //报损
            depotHead.setCustom15(1);
            String lanCode = systemConfigService.getLanCode();
            switch (subType) {
                case "采购":
                case "收费确认":
                    depotHead.setTotalPrice(totalAmount);
                    depotHead.setRemark("zh".equals(lanCode) ? "采购报损" : "Reported loss of purchase");
                    break;
                case "厂家到货":
                    depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
                    depotHead.setRemark("zh".equals(lanCode) ? "销售报损" : "Loss reported on sales");
                    break;
                case "验收":
                    depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
                    depotHead.setRemark("zh".equals(lanCode) ? "验收报损" : "Acceptance report");
                    break;
            }
            depotHead.setUploadFlag("0");
            try {
                depotHeadMapper.insertSelective(depotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }
            DepotHeadExample dhExample = new DepotHeadExample();
            dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
            if (list != null) {
                String headId = list.get(0).getId();
                depotItemService.saveDetials(rows.toString(), headId, "add", request, false);
            }
            audit(depotHead, passDirect, function.getId(), request);
        }
        List<DepotItemVo4WithInfoEx> map = depotItems.stream().collect(Collectors.groupingBy(DepotItemVo4WithInfoEx::getCustom11)).get(2);
        if (null != map && map.size() > 0) {
            depotHead.setId(IdUtils.getUUID());
            String number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                                : "No system prefix is set");
            }
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置税率"
                                : "Untaxed rate");
            }
            //税率
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());

            switch (subType) {
                case "采购":
                    depotHead.setType("出库");
                    depotHead.setSubType("采购退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"CGTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"CGTH" + number);
                    break;
                case "厂家到货":
                    depotHead.setType("其它");
                    depotHead.setSubType("直发销售退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"ZFXXTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"ZFXXTH" + number);
                    break;
                case "收费确认":
                    depotHead.setType("其它");
                    depotHead.setSubType("直发采购退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"ZFCGTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"ZFCGTH" + number);
                    break;
                case "验收":
                    depotHead.setType("其它");
                    depotHead.setSubType("验收退货");
                    depotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"YSTH" + number);
                    depotHead.setNumber(systemConfig.getCompanyPostCode()+"YSTH" + number);
                    break;
            }
            depotHead.setOrganId(depotHead.getOrganId());
            depotHead.setCreateTime(new Date());
            depotHead.setOperTime(new Date());
            depotHead.setCreator(userInfo == null ? null : userInfo.getId());
            depotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            depotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setPurchaseStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            depotHead.setLinkNumber(linkNumber);
            depotHead.setOtherMoney(BigDecimal.ZERO);
            //单据遗留租户 清空
            depotHead.setTenantId(null);
            StringBuilder rows = new StringBuilder("[");
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal taxUnitPrice = BigDecimal.ZERO;
            for (DepotItemVo4WithInfoEx infoEx : map) {
                //单价
                BigDecimal purchaseDecimal =BigDecimal.ZERO;
                BigDecimal discountPrice =BigDecimal.ZERO;
                if ("验收".equals(subType)){
                    purchaseDecimal = infoEx.getPurchaseDecimal();
                }else {
                    purchaseDecimal = infoEx.getUnitPrice();
                    discountPrice = infoEx.getDiscountPrice();
                }
                //数量
                BigDecimal differNumber = infoEx.getDifferNumber();
                amount = purchaseDecimal.multiply(differNumber);

                BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                BigDecimal taxMoney = amount.divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//                BigDecimal taxMoney = taxRate.multiply(amount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                taxUnitPrice = purchaseDecimal.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(amount);
                BigDecimal discountAllPrice = BigDecimal.ZERO;
                if (discountPrice != null && discountPrice.compareTo(BigDecimal.ZERO)>0){
                    discountAllPrice = discountPrice.subtract(purchaseDecimal).multiply(differNumber);
                }

                rows.append("{\"id\":").append("'").append(IdUtils.getUUID()).append("'")
                        .append(",\"depotId\":").append("'").append(infoEx.getDepotId()).append("'")
                        .append(",").append("\"standard\":null,\"model\":").append("'").append(infoEx.getMModel()).append("'")
                        .append(",\"color\":").append("'").append(infoEx.getMColor()).append("'")
                        .append(",\"unit\":").append("'").append(infoEx.getMaterialUnit()).append("'")
                        .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                        .append("\"operNumber\":").append("'").append(differNumber).append("'")
                        .append(",\"unitPrice\":").append("'").append(purchaseDecimal).append("'")
                        .append(",\"allPrice\":").append("'").append(amount).append("'")
                        .append(",\"taxRate\":").append("'").append(taxRate).append("'")
                        .append(",\"custom5\":").append("'").append(infoEx.getCustom5()).append("'")
                        .append(",\"taxMoney\":").append("'").append(taxMoney).append("'")
                        .append(",").append("\"taxLastMoney\":").append("'").append(amount).append("'")
                        .append(",").append("\"taxUnitPrice\":").append("'").append(taxUnitPrice).append("'")
                        .append(",").append("\"discountAllPrice\":").append("'").append(discountAllPrice).append("'")
                        .append(",").append("\"discountPrice\":").append("'").append(discountPrice).append("'")
                        .append(",\"remark\":\"\",\"linkId\":\"\",\"orderNum\":1,\"meId\":").append("'").append(infoEx.getMeId()).append("'").append("}");
            }
            rows.append("]");
            depotHead.setChangeAmount(BigDecimal.ZERO);
            depotHead.setDiscount(BigDecimal.ZERO);
            depotHead.setDiscountMoney(BigDecimal.ZERO);
            depotHead.setDiscountLastMoney(totalAmount);
            //换货
            depotHead.setCustom15(2);
            String lanCode = systemConfigService.getLanCode();
            switch (subType) {
                case "采购":
                case "收费确认":
                    depotHead.setTotalPrice(totalAmount);
                    depotHead.setRemark("zh".equals(lanCode) ? "采购换货" : "Purchase and replacement");
                    break;
                case "厂家到货":
                    depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
                    depotHead.setRemark("zh".equals(lanCode) ? "销售换货" : "Sales replacement");
                    break;
                case "验收":
                    depotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
                    depotHead.setRemark("zh".equals(lanCode) ? "验收换货" : "Acceptance replacement");
                    break;
            }
            depotHead.setUploadFlag("0");
            try {
                depotHeadMapper.insertSelective(depotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }
            DepotHeadExample dhExample = new DepotHeadExample();
            dhExample.createCriteria().andNumberEqualTo(depotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
            if (list != null) {
                String headId = list.get(0).getId();
                depotItemService.saveDetials(rows.toString(), headId, "add", request, false);
            }
            audit(depotHead, passDirect, function.getId(), request);
        }
    }

    private void audit(DepotHead depotHead, boolean passDirect, String functionId, HttpServletRequest request) throws Exception {
        depotHead.setUploadFlag("0");
        if (passDirect) {
            String keyId = userBusinessService.checkValueExist("ConfigRoleFunctions", "[" + functionId + "]", request);
            if (StringUtils.isNotEmpty(keyId)) {
                workflowConfigService.addProcessDetailWithDepot(keyId, depotHead);
            } else {
                depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
                depotHeadMapper.updateByPrimaryKeySelective(depotHead);
                //更新当前库存
                depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
                //修改关联订单状态
                changeBillStatus(depotHead.getId());
            }
        }
    }

    public List<DepotHead> getDepotHeadByOrganId(String organId) {
        List<DepotHead> list = new ArrayList<>();
        try {
            Supplier supplier = supplierMapper.selectByPrimaryKey(organId);
            String type = "";
            String subType = "";
            String type1 = "";
            String subType1 = "";
            if (("供应商").equals(supplier.getType())) {
                type = "入库";
                type1 = "其它";
                subType = "采购";
                subType1 = "收费确认";
            } else if (("客户").equals(supplier.getType())) {
                type = "出库";
                type1 = "到货";
                subType = "销售";
                subType1 = "厂家到货";
            }
            list = depotHeadMapperEx.getDepotHeadByOrganId(organId, type, subType, type1, subType1);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<ReconciliationVoList> getAllBillItemByOrganId(String organId, String beginTime, String endTime, Integer currentPage, Integer pageSize) throws Exception {
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
        List<ReconciliationVoList> list = depotHeadMapperEx.getAllBillItemByOrganId(organId, beginTime, endTime, currentPage, pageSize);
        List<ReconciliationVoList> headVoList = new ArrayList<>();
        if (null != list) {
            for (ReconciliationVoList reconciliationVoList : list) {
                String type = reconciliationVoList.getNewType().replace("其它", "");
                reconciliationVoList.setNewType(type);
                Supplier supplier = supplierService.getSupplier(organId);
                BigDecimal balance = supplierService.getSupplierSum(supplier)
                        .add(supplierService.getSupplierSumByItem(organId, reconciliationVoList.getItemId()))
                        .add(supplierService.getSupplierSumByDepotItem(organId, reconciliationVoList.getItemId()))
                        .add(supplierService.getSupplierSumByDepotHeadNoChangeAmount(organId, reconciliationVoList.getItemId()));
                reconciliationVoList.setBalance(balance);
                headVoList.add(reconciliationVoList);
//                    aEx.setBalance(accountHeadMapperEx.getBalance(organId,aEx.getBillTime()).add(aEx.getTotalPrice()));
            }
        }
        return list;
    }

    public Integer getAllBillItemByOrganIdCount(String organId, String beginTime, String endTime) {
        beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
        endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
        return depotHeadMapperEx.getAllBillItemByOrganIdCount(organId, beginTime, endTime);
    }

    public BigDecimal acceptableQuantity(String id, String materialId) {
        BigDecimal num = BigDecimal.ZERO;
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(id);
        DepotHeadExample depotHeadExample = new DepotHeadExample();
        depotHeadExample.createCriteria().andLinkNumberEqualTo(depotHead.getLinkNumber()).andSubTypeEqualTo("厂家到货").andDeleteFlagEqualTo("0");
        List<DepotHead> depotHeadList = depotHeadMapper.selectByExample(depotHeadExample);
        for (DepotHead head : depotHeadList) {
            DepotItemExample depotItemExample = new DepotItemExample();
            depotItemExample.createCriteria().andHeaderIdEqualTo(head.getId()).andMaterialExtendIdEqualTo(materialId).andDeleteFlagEqualTo("0");
            List<DepotItem> depotItemList = depotItemMapper.selectByExample(depotItemExample);
            for (DepotItem depotItem : depotItemList) {
                num = num.add(depotItem.getOperNumber());
            }
        }
        return num;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void generatorStockTake(String headerId, boolean passDirect, HttpServletRequest request) throws Exception {
        DepotHead depotHead = depotHeadMapper.selectByPrimaryKey(headerId);
        //判断用户是否已经登录过，登录过不再处理
        User userInfo = userService.getCurrentUser();
        List<DepotItemVo4WithInfoEx> detailList = depotItemMapperEx.getDetailList(headerId);
        //差异数为正 则是报损
        List<DepotItemVo4WithInfoEx> outDetailList = detailList.stream().filter(detail -> detail.getDifferNumber().compareTo(BigDecimal.ZERO) < 0 && detail.getCustom12()==0).collect(Collectors.toList());
        List<DepotItemVo4WithInfoEx> inDetailList = detailList.stream().filter(detail -> detail.getDifferNumber().compareTo(BigDecimal.ZERO) > 0 && detail.getCustom12()==0).collect(Collectors.toList());
        String tenantId = depotHead.getTenantId();
        if (outDetailList.size() > 0) {
            DepotHead outDepotHead = new DepotHead();
            outDepotHead.setId(IdUtils.getUUID());
            outDepotHead.setType("出库");
            outDepotHead.setSubType("其它");
            outDepotHead.setLinkNumber(depotHead.getNumber());
            String number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                                : "No system prefix is set");
            }
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置税率"
                                : "Untaxed rate");
            }
            //税率
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());

            outDepotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"QTCK" + number);
            outDepotHead.setNumber(systemConfig.getCompanyPostCode()+"QTCK" + number);
            outDepotHead.setCreateTime(new Date());
            outDepotHead.setOperTime(new Date());
            outDepotHead.setCreator(userInfo == null ? null : userInfo.getId());
            outDepotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            outDepotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            outDepotHead.setDepotId(depotHead.getDepotId());
            outDepotHead.setCustom5(depotHead.getCustom5());
            outDepotHead.setTenantId(tenantId);
            StringBuilder rows = new StringBuilder("[");
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal taxUnitPrice = BigDecimal.ZERO;
            for (DepotItemVo4WithInfoEx infoEx : outDetailList) {
                //单价
                BigDecimal purchaseDecimal = infoEx.getPurchaseDecimal();
                //数量
                BigDecimal differNumber = infoEx.getDifferNumber().abs();
                amount = purchaseDecimal.multiply(differNumber);

                BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                BigDecimal taxMoney = amount.divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//                BigDecimal taxMoney = taxRate.multiply(amount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                taxUnitPrice = purchaseDecimal.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(amount);

                rows.append("{\"id\":").append("'").append(IdUtils.getUUID()).append("'")
                        .append(",\"depotId\":").append("'").append(infoEx.getDepotId()).append("'")
                        .append(",").append("\"standard\":null,\"model\":").append("'").append(infoEx.getMModel()).append("'")
                        .append(",\"color\":").append("'").append(infoEx.getMColor()).append("'")
                        .append(",\"unit\":").append("'").append(infoEx.getMaterialUnit()).append("'")
                        .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                        .append("\"operNumber\":").append("'").append(differNumber).append("'")
                        .append(",\"unitPrice\":").append("'").append(purchaseDecimal).append("'")
                        .append(",\"allPrice\":").append("'").append(amount).append("'")
                        .append(",\"taxRate\":").append("'").append(taxRate).append("'")
                        .append(",\"taxMoney\":").append("'").append(taxMoney).append("'")
                        .append(",\"tenantId\":").append("'").append(tenantId).append("'")
                        .append(",").append("\"taxLastMoney\":").append("'").append(amount).append("'")
                        .append(",").append("\"taxUnitPrice\":").append("'").append(taxUnitPrice).append("'")
                        .append(",").append("linkId:").append("'").append(infoEx.getId()).append("'")
                        .append(",\"remark\":\"\",\"orderNum\":1,\"meId\":").append("'").append(infoEx.getMeId()).append("'").append("}");

            }
            rows.append("]");
            outDepotHead.setTotalPrice(totalAmount);
            outDepotHead.setChangeAmount(BigDecimal.ZERO);
            outDepotHead.setDiscount(BigDecimal.ZERO);
            outDepotHead.setDiscountMoney(BigDecimal.ZERO);
            outDepotHead.setDiscountLastMoney(totalAmount);
            String lanCode = systemConfigService.getLanCode();
            outDepotHead.setRemark("zh".equals(lanCode) ? "盘点报损出库" : "Take stock and report the damage to the warehouse");
            outDepotHead.setUploadFlag("0");
            try {
                 depotHeadMapper.insertSelective(outDepotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }
            DepotHeadExample dhExample = new DepotHeadExample();
            dhExample.createCriteria().andNumberEqualTo(outDepotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
            if (list != null) {
                String headId = list.get(0).getId();
                depotItemService.saveStockTakeDetials(rows.toString(), headId, "add", request, false);
            }
            audit(outDepotHead, passDirect,  request, 2);
        }
        if (inDetailList.size() > 0) {
            DepotHead inDepotHead = new DepotHead();
            inDepotHead.setId(IdUtils.getUUID());
            inDepotHead.setType("入库");
            inDepotHead.setSubType("其它");
            inDepotHead.setLinkNumber(depotHead.getNumber());
            String number = sequenceService.buildOnlyNumber();
            SystemConfig systemConfig = systemConfigService.getSystemConfigByTenantId();
            if (systemConfig == null ||StringUtil.isEmpty(systemConfig.getCompanyPostCode())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置系统前缀"
                                : "No system prefix is set");
            }
            if (StringUtil.isEmpty(systemConfig.getCompanyContacts())){
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                        "zh".equals(systemConfigService.getLanCode()) ? "未设置税率"
                                : "Untaxed rate");
            }
            //税率
            BigDecimal taxRate = new BigDecimal(systemConfig.getCompanyContacts());

            inDepotHead.setDefaultNumber(systemConfig.getCompanyPostCode()+"QTRK" + number);
            inDepotHead.setNumber(systemConfig.getCompanyPostCode()+"QTRK" + number);
            inDepotHead.setCreateTime(new Date());
            inDepotHead.setOperTime(new Date());
            inDepotHead.setCreator(userInfo == null ? null : userInfo.getId());
            inDepotHead.setCreateTime(new Timestamp(System.currentTimeMillis()));
            inDepotHead.setStatus(BusinessConstants.BILLS_STATUS_UN_AUDIT);
            inDepotHead.setDepotId(depotHead.getDepotId());
            inDepotHead.setCustom5(depotHead.getCustom5());
            inDepotHead.setTenantId(tenantId);
            inDepotHead.setPayType("现付");
            StringBuilder rows = new StringBuilder("[");
            BigDecimal totalAmount = BigDecimal.ZERO;
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal taxUnitPrice = BigDecimal.ZERO;
            for (DepotItemVo4WithInfoEx infoEx : inDetailList) {
                //单价
                BigDecimal purchaseDecimal = infoEx.getPurchaseDecimal();
                //数量
                BigDecimal differNumber = infoEx.getDifferNumber().abs();
                amount = purchaseDecimal.multiply(differNumber);

                BigDecimal newTaxRate = taxRate.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal newTaxMoneyRate = BigDecimal.ONE.add(newTaxRate);
                BigDecimal taxMoney = amount.divide(newTaxMoneyRate, 2, BigDecimal.ROUND_HALF_UP).multiply(newTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);

//                BigDecimal taxMoney = taxRate.multiply(amount).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                taxUnitPrice = purchaseDecimal.divide(new BigDecimal("1.1"), 2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(amount);

                rows.append("{\"id\":").append("'").append(IdUtils.getUUID()).append("'")
                        .append(",\"depotId\":").append("'").append(infoEx.getDepotId()).append("'")
                        .append(",").append("\"standard\":null,\"model\":").append("'").append(infoEx.getMModel()).append("'")
                        .append(",\"color\":").append("'").append(infoEx.getMColor()).append("'")
                        .append(",\"unit\":").append("'").append(infoEx.getMaterialUnit()).append("'")
                        .append(",\"sku\":\"\",\"preNumber\":\"\",\"finishNumber\":\"\",")
                        .append("\"operNumber\":").append("'").append(differNumber).append("'")
                        .append(",\"unitPrice\":").append("'").append(purchaseDecimal).append("'")
                        .append(",\"allPrice\":").append("'").append(amount).append("'")
                        .append(",\"taxRate\":").append("'").append(taxRate).append("'")
                        .append(",\"taxMoney\":").append("'").append(taxMoney).append("'")
                        .append(",\"tenantId\":").append("'").append(tenantId).append("'")
                        .append(",").append("\"taxLastMoney\":").append("'").append(amount).append("'")
                        .append(",").append("\"taxUnitPrice\":").append("'").append(taxUnitPrice).append("'")
                        .append(",").append("\"linkId\":").append("'").append(infoEx.getId()).append("'")
                        .append(",\"remark\":\"\",\"orderNum\":1,\"meId\":").append("'").append(infoEx.getMeId()).append("'").append("}");

            }
            rows.append("]");
            inDepotHead.setTotalPrice(BigDecimal.ZERO.subtract(totalAmount));
            inDepotHead.setChangeAmount(BigDecimal.ZERO);
            inDepotHead.setDiscount(BigDecimal.ZERO);
            inDepotHead.setDiscountMoney(BigDecimal.ZERO);
            inDepotHead.setDiscountLastMoney(totalAmount);
            String lanCode = systemConfigService.getLanCode();
            inDepotHead.setRemark("zh".equals(lanCode) ? "盘点报溢入库" : "Inventory report overflow into storage");
            inDepotHead.setUploadFlag("0");
            try {
                 depotHeadMapper.insertSelective(inDepotHead);
            } catch (Exception e) {
                JshException.writeFail(logger, e, systemConfigService.getLanCode());
            }
            DepotHeadExample dhExample = new DepotHeadExample();
            dhExample.createCriteria().andNumberEqualTo(inDepotHead.getNumber()).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<DepotHead> list = depotHeadMapper.selectByExample(dhExample);
            if (list != null) {
                String headId = list.get(0).getId();
                depotItemService.saveStockTakeDetials(rows.toString(), headId, "add", request, false);
            }
            audit(inDepotHead, passDirect,  request, 1);
        }
        int takeStockDepotItemStatus = depotItemService.getTakeStockDepotItemStatus(headerId);
        if (takeStockDepotItemStatus <=0){
            depotHead.setStatus("2");
            depotHead.setUploadFlag("0");
            depotHeadMapper.updateByPrimaryKeySelective(depotHead);
        }
    }

    private void audit(DepotHead depotHead, boolean passDirect,  HttpServletRequest request, Integer functionType) throws Exception {
        depotHead.setUploadFlag("0");
        if (passDirect) {
            Function function = new Function();
            switch (functionType){
                case 1:
                    function = functionService.findByName("其它入库");
                    break;
                case 2:
                    function = functionService.findByName("其它出库");
                    break;
            }

            String keyId = userBusinessService.checkValueExist("ConfigRoleFunctions", "[" + function.getId() + "]", request);
            if (StringUtils.isNotEmpty(keyId)) {
                workflowConfigService.addProcessDetailWithDepot(keyId, depotHead);
            } else {
                depotHead.setStatus(BusinessConstants.BILLS_STATUS_AUDIT);
                depotHeadMapper.updateByPrimaryKeySelective(depotHead);
                //更新当前库存
                depotItemService.updateCurrentStockByHeaderId(depotHead.getId(),true);
                //修改关联订单状态
                changeBillStatus(depotHead.getId());
                //盘点单状态
                depotItemService.getTakeStockDepotHead(depotHead.getId());
            }
        }
    }

    public List<DepotHeadVo4List> getHeadByLinkNumber(String number) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();
        List<DepotHeadVo4List> list = null;
        try {
//            DepotHeadExample example=new DepotHeadExample();
//            example.createCriteria().andLinkNumberEqualTo(number).andTypeNotEqualTo("厂家报价").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = depotHeadMapperEx.getHeadByLinkNumber(number);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if ("采购退货".equals(dh.getSubType()) || "销售退货".equals(dh.getSubType())
                            || "直发采购退货".equals(dh.getSubType())|| "直发销售退货".equals(dh.getSubType())) {
                        dh.setTotalPrice(BigDecimal.ZERO.subtract(dh.getTotalPrice()));
                        dh.setDiscountLastMoney(BigDecimal.ZERO.subtract(dh.getDiscountLastMoney()));
                    }
                    dh.setFinishDebt(accountItemService.getEachAmountByBillId(dh.getId()));
                    dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    if (StringUtil.isNotEmpty(dh.getCreator())){
                        User user = userService.getUser(dh.getCreator());
                        if (user != null) {
                            dh.setCreatorName(user.getLoginName());
                        }
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<DepotHeadVo4List> getInHeadByLinkNumber(String number) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();
        List<DepotHeadVo4List> list = null;
        try {
//            DepotHeadExample example=new DepotHeadExample();
//            example.createCriteria().andLinkNumberEqualTo(number).andTypeNotEqualTo("厂家报价").andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = depotHeadMapperEx.getInHeadByLinkNumber(number);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    if (StringUtil.isNotEmpty(dh.getCreator())){
                        User user = userService.getUser(dh.getCreator());
                        if (user != null) {
                            dh.setCreatorName(user.getLoginName());
                        }
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<AccountHeadWIthPaymentWarning> paymentWarning(String organId, String number, String beginTime, String endTime,
                                                              String status, Integer currentPage, Integer pageSize, Integer day) {
        List<AccountHeadWIthPaymentWarning> resList = new ArrayList<>();
        try {
            String depotIds = depotService.findDepotStrByCurrentUser();
            String[] depotArray = depotIds.split(",");
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<AccountHeadWIthPaymentWarning> list = depotHeadMapperEx.paymentWarning(organId, status, number, beginTime,
                    endTime, depotArray, currentPage, pageSize, day);
            if (null != list) {
                for (AccountHeadWIthPaymentWarning dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getDateWarning() != null) {
                        dh.setDateWarningStr(getCenternTime(dh.getDateWarning()));
                    }
                    if (dh.getFinishNumber().compareTo(BigDecimal.ZERO) > 0) {
                        dh.setNotFinishNumber(dh.getOperNumber().subtract(dh.getFinishNumber()));
                    } else {
                        dh.setNotFinishNumber(dh.getFinishNumber());
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<AccountHeadWIthTracking> purchaseOrderTracking(String organId, String number, String beginTime, String endTime,
                                                               String depotId, Integer currentPage, Integer pageSize, String materialName) {
        List<AccountHeadWIthTracking> resList = new ArrayList<>();
        try {
            String depotIds = depotService.findDepotStrByCurrentUser();
            String[] depotArray = depotIds.split(",");
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<AccountHeadWIthTracking> list = depotHeadMapperEx.purchaseOrderTracking(organId, depotId, number, beginTime,
                    endTime, depotArray, currentPage, pageSize, materialName);
            if (null != list) {
                for (AccountHeadWIthTracking dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
//                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<DepotHeadTraceDetail> trackingDetailList(String linkNumber, String type, String subType, Integer orderType) {
        List<DepotHeadTraceDetail> list = null;
        try {
            if ("采购订单".equals(subType)||"厂家直发".equals(subType)||"销售订单".equals(subType)) {
                list = depotHeadMapperEx.getPurchaseDetail(linkNumber);
            } else if ("采购退货".equals(subType)) {
                //报损-换货
                if (orderType == 1 || orderType == 2) {
                    list = depotHeadMapperEx.breakOrChangeDetail(linkNumber, type, subType, orderType);
                }
            }else if("直发销售退货".equals(subType)){
                //报损-换货
                if (orderType == 1 || orderType == 2) {
                    list = depotHeadMapperEx.breakOrChangeDetailByStraight(linkNumber, type, subType, orderType);
                }
            }else if("销售退货".equals(subType)){
                //报损-换货
                if (orderType == 1 || orderType == 2) {
                    list = depotHeadMapperEx.breakOrChangeDetailBySales(linkNumber, type, subType, orderType);
                }
            }else if("直发厂家报价".equals(subType) ||"收费确认".equals(subType)){
                list = depotHeadMapperEx.straightTrackingDetailList(linkNumber, type, subType);
            } else {
                list = depotHeadMapperEx.trackingDetailList(linkNumber, type, subType);
            }
            if (null != list && list.size() > 0) {
                for (DepotHeadTraceDetail depotHeadTraceDetail : list) {
                    String newType = depotHeadTraceDetail.getNewType().replace("其它", "");
                    depotHeadTraceDetail.setNewType(newType);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public List<DepotHeadTraceDetail> factoryOutLetDetails(String linkNumber, String type, String subType, Integer orderType) {
        List<DepotHeadTraceDetail> list = null;
        try {
            if ("厂家直发".equals(subType)) {
                list = depotHeadMapperEx.getPurchaseDetail(linkNumber);
            } else if ("采购退货".equals(subType)) {
                if (orderType == 1) {
                    //报损
                    list = depotHeadMapperEx.breakOrChangeDetail(linkNumber, type, subType, orderType);
                } else if (orderType == 2) {
                    //换货
                    list = depotHeadMapperEx.breakOrChangeDetail(linkNumber, type, subType, orderType);
                }
            } else {
                list = depotHeadMapperEx.trackingDetailList(linkNumber, type, subType);
            }
            if (null != list && list.size() > 0) {
                for (DepotHeadTraceDetail depotHeadTraceDetail : list) {
                    String newType = depotHeadTraceDetail.getNewType().replace("其它", "");
                    depotHeadTraceDetail.setNewType(newType);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Map<String, Object>> getSaleShoppingRunningWater(String beginTime, String endTime,
                                                                 List<String> depotList, Integer offset, Integer rows, String orderNumber) throws Exception  {
        List<DepotHeadWithPos> list = null;
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String, String> accountMap = accountService.getAccountMap();
        try {
            list = depotHeadMapperEx.getSaleShoppingRunningWater(beginTime, endTime, depotList, orderNumber, offset, rows);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithPos dep : list) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", dep.getId());
                    map.put("order_no", dep.getNumber());
                    map.put("add_time", dep.getOperTime());
                    map.put("settlement_type", 1);
                    map.put("order_type", dep.getOrderType());
                    map.put("all_money", dep.getTotalPrice());
                    map.put("payType", dep.getPayType());
                    map.put("pay_status", dep.getStatus());
                    map.put("pay_money", dep.getChangeAmount());
                    map.put("vip_class", "散客");
                    map.put("amount_received", dep.getChangeAmount().add(dep.getBackAmount()));
                    map.put("give_change", dep.getBackAmount());
                    map.put("goods_info", dep.getMaterialList());
                    if (accountMap != null && StringUtil.isNotEmpty(dep.getAccountIdList()) && StringUtil.isNotEmpty(dep.getAccountMoneyList())) {
                        String accountStr = accountService.getPosAccountStrByIdAndMoney(accountMap, dep.getAccountIdList(), dep.getAccountMoneyList());
                        map.put("accountName", accountStr);
                    }
                    if (StringUtil.isNotEmpty(dep.getAccount())){
                        String accountStr= dep.getAccount()+"(" + dep.getChangeAmount().stripTrailingZeros().toPlainString()+ ") ";
                        map.put("accountName", accountStr);
                    }
                    User user = userService.getUser(dep.getSalesMan());
                    if (null !=user){
                        map.put("salesManStr", user.getLoginName());
                    }
                    mapList.add(map);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return mapList;
    }

    public int getSaleShoppingRunningWaterCount(String beginTime, String endTime, List<String> depotList, String orderNumber) {
        int result = 0;
        try {
            result = depotHeadMapperEx.getSaleShoppingRunningWaterCount(beginTime, endTime, depotList, orderNumber);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public List<DepotHeadWithStaffSales> findPromotionCreatorCount(String creator, String beginTime, String endTime,
                                                                   Integer offset, Integer rows,String organId) throws Exception {
        List<DepotHeadWithStaffSales> resList = new ArrayList<>();
        List<DepotHeadWithStaffSales> list = null;
        try {
            list = depotHeadMapperEx.findPromotionCreatorCount(creator, beginTime, endTime, offset, rows,organId);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithStaffSales m : list) {
                    BigDecimal returnPrice = depotHeadMapperEx.findReturnPriceByCreator(m.getCreator(), beginTime, endTime)==null ? BigDecimal.ZERO:depotHeadMapperEx.findReturnPriceByCreator(m.getCreator(), beginTime, endTime);
                    BigDecimal discountLastMoney = m.getDiscountLastMoney();
                    m.setDiscountLastMoney(discountLastMoney.subtract(m.getTaxMoney()));
                    m.setSalesReturnPrice(returnPrice);
                    m.setAllPrice(discountLastMoney.subtract(returnPrice));
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
    public int findPromotionCreatorCountTotal(String creator, String beginTime, String endTime,String organId) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findPromotionCreatorCountTotal(creator, beginTime, endTime,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadWithStaffSalesDetail> findDepotByCreatorDetail(String creator, String beginTime, String endTime,
                                                                   Integer offset, Integer rows,String organId) throws Exception {
        List<DepotHeadWithStaffSalesDetail> resList = new ArrayList<>();
        List<DepotHeadWithStaffSalesDetail> list = null;
        try {
            list = depotHeadMapperEx.findDepotByCreatorDetail(creator, beginTime, endTime, offset, rows,organId);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithStaffSalesDetail m : list) {
                    String newType = m.getNewType().replace("其它", "");
                    m.setNewType(newType);
                    m.setOperTimeStr(getCenternTime(m.getOperTime()));
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public int findDepotByCreatorDetailTotal(String creator, String beginTime, String endTime,String organId) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findDepotByCreatorDetailTotal(creator, beginTime, endTime,organId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadWithRebate> findRebate(String creator, String organId,String number,Integer custom12,
                                                    String beginTime, String endTime,Integer offset, Integer rows) throws Exception {
        List<DepotHeadWithRebate> resList = new ArrayList<>();
        List<DepotHeadWithRebate> list = null;
        try {
            list = depotHeadMapperEx.findRebate(creator,organId,number,custom12, beginTime, endTime, offset, rows);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithRebate m : list) {
                    m.setCreateTimeStr(getCenternTime(m.getCreateTime()));
                    m.setOperTimeStr(getCenternTime(m.getOperTime()));
                    m.setReceivableAmount(m.getCustom10().subtract(m.getCustom9()));
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
    public int findRebateTotal(String creator,String organId,String number,Integer custom12,
                               String beginTime, String endTime) throws Exception {
        int result = 0;
        try {
            result = depotHeadMapperEx.findRebateTotal(creator,organId,number,custom12, beginTime, endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public int updateDepotHeadByRebate(AccountHead accountHead,String actionType) throws Exception {
        String number = accountHead.getNumber();
        String id = accountHead.getId();
        BigDecimal payAmount=accountHead.getChangeAmount();
        DepotHead depotHead = getDepotHead(number);
        depotHead.setUploadFlag("0");
        if ("add".equals(actionType)){
            depotHead.setCustom9(depotHead.getCustom9().add(payAmount));
        }else if ("update".equals(actionType)) {
            BigDecimal accountByRebate = accountHeadService.getAccountByRebate(number, id);
            depotHead.setCustom9(accountByRebate.add(payAmount));

        }else if ("delete".equals(actionType)) {
            depotHead.setCustom9(depotHead.getCustom9().subtract(payAmount));

        }
        if (depotHead.getCustom9().compareTo(depotHead.getCustom10())>=0){
            depotHead.setCustom12(1);
        }else if (depotHead.getCustom9().compareTo(BigDecimal.ZERO)==0){
            depotHead.setCustom12(0);
        }else {
            depotHead.setCustom12(2);
        }
        return depotHeadMapper.updateByPrimaryKeySelective(depotHead);
    }
    public int updateCustom12ByBillId(String billId) throws Exception {
        int i=0;
        try {
            i=depotHeadMapperEx.updateCustom12ByBillId(billId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    public List<DepotHeadVo4List> selectSalesOrderByConditionDepotHead(String type, String subType, String status, String number,
                                         String beginTime, String endTime, String materialParam,int offset, int rows) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = depotHeadMapperEx.selectSalesOrderByConditionDepotHead(typeList, subTypeList,  statusArray,  number,  beginTime, endTime,
                    materialParam,   offset, rows);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if (dh.getDeposit() == null) {
                        dh.setDeposit(BigDecimal.ZERO);
                    }
                    if (StringUtil.isNotEmpty(dh.getDepotId())) {
                        dh.setDepotName(depotService.getAnotherDepotById(dh.getDepotId()));
                    }
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if ("销售订单".equals(dh.getSubType())){
                        dh.setStraightDeposit(accountHeadMapperEx.getDepositByNumber(dh.getNumber(),"4"));
                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    dh.setTotal(depotHeadMapperEx.getTotal(dh.getDefaultNumber()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public Long countsSalesOrderByDepotHead(String type, String subType, String status, String number,
                               String beginTime, String endTime, String materialParam) throws Exception {
        Long result = null;
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            result = depotHeadMapperEx.countsSalesOrderByDepotHead(typeList, subTypeList, statusArray,  number,  beginTime, endTime,
                    materialParam);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public List<DepotHeadVo4List> getSalesHeadByLinkNumber(String number) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<DepotHeadVo4List>();
        List<DepotHeadVo4List> list = null;
        try {
            list = depotHeadMapperEx.getSalesHeadByLinkNumber(number);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if ("采购退货".equals(dh.getSubType()) || "销售退货".equals(dh.getSubType())
                            || "直发采购退货".equals(dh.getSubType())|| "直发销售退货".equals(dh.getSubType())) {
                        dh.setTotalPrice(BigDecimal.ZERO.subtract(dh.getTotalPrice()));
                        dh.setDiscountLastMoney(BigDecimal.ZERO.subtract(dh.getDiscountLastMoney()));
                    }
                    dh.setFinishDebt(accountItemService.getEachAmountByBillId(dh.getId()));
                    dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    if (StringUtil.isNotEmpty(dh.getCreator())){
                        User user = userService.getUser(dh.getCreator());
                        if (user != null) {
                            dh.setCreatorName(user.getLoginName());
                        }
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<DepotHeadWithItem> findPromotionMaterialDetail(String beginTime, String endTime, String type, String materialParam,
                                                List<String> depotList, String oId, String number, String remark, Integer offset,
                                                Integer rows,String subType,String creator,List<String> idList) throws Exception {
        List<DepotHeadWithItem> list = null;
        try {
            list = depotHeadMapperEx.findPromotionMaterialDetail(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, offset, rows,subType,creator,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public Long findPromotionMaterialDetailTotal(String beginTime, String endTime, String type, String materialParam,
                                                List<String> depotList, String oId, String number, String remark,String subType,String creator,
                                                 List<String> idList) throws Exception {
        Long result = null;
        try {
            result = depotHeadMapperEx.findPromotionMaterialDetailTotal(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, subType,creator,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DepotHeadWithItem> findCheckMaterialDetail(String beginTime, String endTime, String type, String materialParam,
                                                               List<String> depotList, String oId, String number, String remark, Integer offset,
                                                               Integer rows,String subType,String creator,String materialId,List<String> idList) throws Exception {
        List<DepotHeadWithItem> list = null;
        try {
            list = synchronizationTaskMapperEx.findCheckMaterialDetail(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, offset, rows,subType,creator,materialId,idList);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithItem depotHeadWithItem : list) {
                    String newType = depotHeadWithItem.getNewType().replace("其它", "");
                    depotHeadWithItem.setNewType(newType);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public Long findCheckMaterialDetailTotal(String beginTime, String endTime, String type, String materialParam,
                                                 List<String> depotList, String oId, String number, String remark,
                                             String subType,String creator,String materialId,List<String> idList) throws Exception {
        Long result = null;
        try {
            result = synchronizationTaskMapperEx.findCheckMaterialDetailTotal(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, subType,creator,materialId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public List<DepotHeadWithItem> findPackageMaterialDetail(String beginTime, String endTime, String type, String materialParam,
                                                               List<String> depotList, String oId, String number, String remark, Integer offset,
                                                               Integer rows,String subType,String creator, List<String> idList) throws Exception {
        List<DepotHeadWithItem> list = null;
        try {
            list = depotHeadMapperEx.findPackageMaterialDetail(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, offset, rows,subType,creator,idList);
            if (null != list && list.size() > 0) {
                for (DepotHeadWithItem depotHeadWithItem : list) {
                    String newType = depotHeadWithItem.getNewType().replace("其它", "");
                    depotHeadWithItem.setNewType(newType);
                    if(("组装单".equals(depotHeadWithItem.getSubType()) && "组合件".equals(depotHeadWithItem.getMaterialType()))
                            || ("拆卸单".equals(depotHeadWithItem.getSubType()) && "普通子件".equals(depotHeadWithItem.getMaterialType())) ){

                    }else if(("组装单".equals(depotHeadWithItem.getSubType()) && "普通子件".equals(depotHeadWithItem.getMaterialType()))
                            || ("拆卸单".equals(depotHeadWithItem.getSubType()) && "组合件".equals(depotHeadWithItem.getMaterialType())) ){
                        depotHeadWithItem.setOperNumber(BigDecimal.ZERO.subtract(depotHeadWithItem.getOperNumber()));
                        depotHeadWithItem.setAllPrice(BigDecimal.ZERO.subtract(depotHeadWithItem.getAllPrice()));
                    }
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public Long findPackageMaterialDetailTotal(String beginTime, String endTime, String type, String materialParam,
                                                 List<String> depotList, String oId, String number, String remark,String subType,String creator, List<String> idList) throws Exception {
        Long result = null;
        try {
            result = depotHeadMapperEx.findPackageMaterialDetailTotal(beginTime, endTime, type, materialParam, depotList, oId, number,
                    remark, subType,creator,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<SalesMarginDetailVo> findSalesMarginDetail(String beginTime, String endTime,List<String> depotList,
                                                       String oId,Integer offset,Integer rows,String creator,
                                                       Integer marginType,String materialName,String materialId,List<String> idList) throws Exception {
        List<SalesMarginDetailVo> list = null;
        try {
            list = depotHeadMapperEx.findSalesMarginDetail(beginTime, endTime, depotList, oId,
                     offset, rows,creator,marginType,materialName,materialId,idList);
            if (null != list && list.size() > 0) {
                for (SalesMarginDetailVo salesMarginVo : list) {
                    if (null == salesMarginVo.getSalesRevenue() || salesMarginVo.getSalesRevenue().compareTo(BigDecimal.ZERO) == 0
                            ||null == salesMarginVo.getSalesCost() || salesMarginVo.getSalesCost().compareTo(BigDecimal.ZERO) == 0){
                        salesMarginVo.setSalesRevenue(BigDecimal.ZERO);
                        salesMarginVo.setSalesGrossMargin(BigDecimal.ZERO);
                    }else {
                        BigDecimal salesMargin = salesMarginVo.getSalesRevenue().subtract(salesMarginVo.getSalesCost());
                        salesMarginVo.setSalesMargin(salesMargin);
                        BigDecimal salesGrossMargin = salesMargin.divide(salesMarginVo.getSalesRevenue(), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                        salesMarginVo.setSalesGrossMargin(salesGrossMargin);
                    }

                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public Long findSalesMarginDetailTotal(String beginTime, String endTime,List<String> depotList,
                                         String oId,String creator,Integer marginType,String materialName,String materialId,
                                           List<String> idList) throws Exception {
        Long result = null;
        try {
            result = depotHeadMapperEx.findSalesMarginDetailTotal(beginTime, endTime,  depotList, oId,
                     creator,marginType,materialName,materialId,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<SalesMarginVo> findSalesMarginList(String beginTime, String endTime,List<String> depotList,
                                                   String oId,Integer offset,Integer rows,String creator,
                                                   Integer marginType,String materialName) throws Exception {
        List<SalesMarginVo> list = null;
        try {
            list = depotHeadMapperEx.findSalesMarginList(beginTime, endTime, depotList, oId,
                    offset, rows,creator,marginType,materialName);
            if (null != list && list.size() > 0) {
                for (SalesMarginVo salesMarginVo : list) {
                    if (null == salesMarginVo.getSalesRevenue() || salesMarginVo.getSalesRevenue().compareTo(BigDecimal.ZERO) == 0
                        ||null == salesMarginVo.getSalesCost() || salesMarginVo.getSalesCost().compareTo(BigDecimal.ZERO) == 0){
                        salesMarginVo.setSalesRevenue(BigDecimal.ZERO);
                        salesMarginVo.setSalesGrossMargin(BigDecimal.ZERO);
                    }else {
                        BigDecimal salesMargin = salesMarginVo.getSalesRevenue().subtract(salesMarginVo.getSalesCost());
                        salesMarginVo.setSalesMargin(salesMargin);
                        BigDecimal salesGrossMargin = salesMargin.divide(salesMarginVo.getSalesRevenue(), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
                        salesMarginVo.setSalesGrossMargin(salesGrossMargin);
                    }

                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public Long findSalesMarginListTotal(String beginTime, String endTime,List<String> depotList,
                                         String oId,String creator,Integer marginType,String materialName) throws Exception {
        Long result = null;
        try {
            result = depotHeadMapperEx.findSalesMarginListTotal(beginTime, endTime,  depotList, oId,
                    creator,marginType,materialName);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public Depot getTenantIdByDepotId(String number) throws Exception {
        Depot depot =null;
        try {
            DepotHead depotHead = getDepotHead(number);
            depot = depotMapperEx.getAnotherDepotById(depotHead.getDepotId());
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depot;
    }

    public List<DailySales> findDailySales(String beginTime, String endTime, Integer offset, Integer rows, String tenantId) {
        List<DailySales> resList = new ArrayList<DailySales>();
        List<DailySales> list = null;
        try {
            list = synchronizationTaskMapperEx.findDailySales(beginTime, endTime, offset, rows, tenantId);
            if (null != list) {
                for (DailySales dh : list) {
                    BigDecimal discountLastMoney = dh.getDiscountLastMoney();
                    if (dh.getRefunds() !=null && dh.getRefunds().compareTo(BigDecimal.ZERO)>0 ){
                        dh.setDiscountLastMoney(dh.getDiscountLastMoney().subtract(dh.getRefunds()));
                    }
                    if (dh.getRefundsDiscount() != null && dh.getRefundsDiscount().compareTo(BigDecimal.ZERO)>0){
                        dh.setDiscount(dh.getDiscount().subtract(dh.getRefundsDiscount()));
                    }
                    dh.setAllPrice(discountLastMoney.add(dh.getDiscount()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public int findDailySalesTotal(String beginTime, String endTime, String tenantId ) {
        int result = 0;
        try {

            result = synchronizationTaskMapperEx.findDailySalesTotal(beginTime, endTime,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DailySalesUserVo> getDailySalesDetail(String beginTime, String endTime, Integer offset, Integer rows, String tenantId) {
        List<DailySalesUserVo> userVos=new ArrayList<>();
        List<DailySalesUser> list = null;
        List<User> userList = null;
        try {
            userList = userService.getUserListByTenantId(tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        if (userList !=null && userList.size()>0){
            for (User user:userList){
                try {
                    list = synchronizationTaskMapperEx.getDailySalesDetail(beginTime, endTime, offset, rows, user.getId());
                    if (null != list && list.size()>0) {
                        DailySalesUserVo userVo=new DailySalesUserVo();
                        List<DailySalesUser> resList = new ArrayList<DailySalesUser>();
                        for (DailySalesUser dh : list) {
                            if (dh.getRefunds() != null){
                                dh.setAmount(dh.getActualAmount().subtract(dh.getRefunds()));
                            }else {
                                dh.setAmount(dh.getActualAmount());
                            }
                            resList.add(dh);
                        }
                        userVo.setUser(user);
                        userVo.setSalesUserList(resList);
                        userVos.add(userVo);
                    }
                } catch (Exception e) {
                    JshException.readFail(logger, e, systemConfigService.getLanCode());
                }
            }
        }

        return userVos;
    }

//    public int getDailySalesDetailTotal(String beginTime, String endTime, String creator) {
//        int result = 0;
//        try {
//
//            result = synchronizationTaskMapperEx.getDailySalesDetailTotal(beginTime, endTime, creator);
//        } catch (Exception e) {
//            JshException.readFail(logger, e, systemConfigService.getLanCode());
//        }
//        return result;
//    }

    public BigDecimal totalCreditPayment(String beginTime, String endTime,String tenantId) {
        BigDecimal totalCreditPayment =BigDecimal.ZERO;
        try {
            totalCreditPayment = synchronizationTaskMapperEx.totalCreditPayment(beginTime, endTime,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return totalCreditPayment;
    }

    public List<AccountHeadCreditPayment> creditPayment(String beginTime, String endTime,String tenantId) {
        List<AccountHeadCreditPayment> list =null;
        try {
            list = synchronizationTaskMapperEx.creditPayment(beginTime, endTime,tenantId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

   public List<DailySales> creditInvoices(String beginTime, String endTime,String tenantId) {
       List<DailySales> resList = new ArrayList<DailySales>();
       List<DailySales> list =null;
        try {
            list = synchronizationTaskMapperEx.creditInvoices(beginTime, endTime,tenantId);
            if (null != list) {
                for (DailySales dh : list) {
                    BigDecimal discountLastMoney = dh.getDiscountLastMoney();
                    if (dh.getRefunds() !=null && dh.getRefunds().compareTo(BigDecimal.ZERO)>0 ){
                        dh.setDiscountLastMoney(dh.getDiscountLastMoney().subtract(dh.getRefunds()));
                    }
                    if (dh.getRefundsDiscount() != null && dh.getRefundsDiscount().compareTo(BigDecimal.ZERO)>0){
                        dh.setDiscount(dh.getDiscount().subtract(dh.getRefundsDiscount()));
                    }
                    dh.setAllPrice(discountLastMoney.add(dh.getDiscount()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public List<DailySummarySalesVo> getDailySummarySales(String beginTime, String endTime) {
//        Map<String,Object> map= new HashMap<>();
//        Map<String,Map<String,Object>> dateMap= new HashMap<>();
        List<DailySummarySalesVo> resList=new ArrayList<>();

        try {
//            List<Tenant> tenants = synchronizationTaskMapperEx.selectTenantTime();
//            if (tenants !=null && tenants.size()>0) {
//                List<String> tenantIdList = tenants.stream().map(Tenant::getId).collect(Collectors.toList());
                List<String> dateList = Tools.getDateList(beginTime, endTime);
                if (dateList.size() > 0) {
                    for (String dateStr:dateList){
                        List<DailySummarySales> dailySummarySales = synchronizationTaskMapperEx.getDailySummarySales(null, dateStr);
                        DailySummarySalesVo dailySummarySalesVo=new DailySummarySalesVo();
                        dailySummarySalesVo.setDays(dateStr);
                        dailySummarySalesVo.setList(dailySummarySales);
                        resList.add(dailySummarySalesVo);
                    }
                }
//            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
    public List<SalesOrderTracking> salesOrderTracking(String organId, String number, String beginTime, String endTime,
                                                               String depotId, Integer currentPage, Integer pageSize) {
        List<SalesOrderTracking> resList = new ArrayList<>();
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            List<SalesOrderTracking> list = depotHeadMapperEx.salesOrderTracking(organId, depotId, number, beginTime,
                    endTime,  currentPage, pageSize);
            if (null != list) {
                for (SalesOrderTracking dh : list) {
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    StringBuilder sb=new StringBuilder();
                    String lanCode = systemConfigService.getLanCode();
                    if (dh.getDeduction() != null && dh.getDeduction().compareTo(BigDecimal.ZERO)>0){
                        if ("zh".equals(lanCode)){
                            sb.append("抵扣：").append(dh.getDeduction()).append(",");
                        }else {
                            sb.append("Deduction：").append(dh.getDeduction()).append(",");
                        }
                    }
                    if (dh.getAmount() != null && dh.getAmount().compareTo(BigDecimal.ZERO)>0){
                        if ("zh".equals(lanCode)){
                            sb.append("实际金额：").append(dh.getAmount()).append(",");
                        }else {
                            sb.append("Actual Amount：").append(dh.getAmount()).append(",");
                        }
                    }
                    dh.setAmountCollectedStr(sb.toString());
                    dh.setOutNumber(dh.getFinishNumber().subtract(dh.getBreakNumber()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
    public List<TransferSummary> transferSummary(List<String> depotList, String materialName, String beginTime, String endTime,
                                                       Integer currentPage, Integer pageSize,List<String> idList) {
        List<TransferSummary> list = null;
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = synchronizationTaskMapperEx.transferSummary(depotList,  materialName, beginTime,
                    endTime,  currentPage, pageSize,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public List<DepotHeadVo4InDetail> transferSummaryDetail(List<String> depotList, String materialId, String beginTime, String endTime,
                                                       Integer currentPage, Integer pageSize) {
        List<DepotHeadVo4InDetail> resList = new ArrayList<>();
        List<DepotHeadVo4InDetail> list = null;
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = synchronizationTaskMapperEx.transferSummaryDetail(depotList,  materialId, beginTime,
                    endTime,  currentPage, pageSize);
            if (null != list && list.size() > 0) {
                for (DepotHeadVo4InDetail m : list) {
                    if (m.getPurchaseDecimal()!=null && m.getPurchaseDecimal().compareTo(BigDecimal.ZERO)>0){
                        m.setAllPrice(m.getPurchaseDecimal().multiply(m.getOperNumber()));
                    }
                    resList.add(m);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
    public List<TransferSummary> otherSummary(List<String> depotList, String materialName, String beginTime, String endTime,
                                                       Integer currentPage, Integer pageSize,List<String> idList) {
        List<TransferSummary> list = null;
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = synchronizationTaskMapperEx.otherSummary(depotList,  materialName, beginTime,
                    endTime,  currentPage, pageSize,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public List<TakeStockSummary> takeStockSummary(List<String> depotList, String materialName, String beginTime, String endTime,
                                              Integer currentPage, Integer pageSize,List<String> idList) {
        List<TakeStockSummary> list = null;
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = synchronizationTaskMapperEx.takeStockSummary(depotList,  materialName, beginTime,
                    endTime,  currentPage, pageSize,idList);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }


    public List<DepotHeadVo4List> selectAllot(String type, String subType, String roleType, String status, String purchaseStatus, String number, String linkNumber,
                                         String beginTime, String endTime, String materialParam, String organId, String creator, String depotId, String accountId,
                                         String remark, String custom3, int offset, int rows, String payStatus, String freightStatus, String quotationStatus,
                                         String custom4,String color,String alwaysSelect,String itemType,String creditStatus,String depotStatus) throws Exception {
        List<DepotHeadVo4List> resList = new ArrayList<>();
        List<DepotHeadVo4List> list = new ArrayList<>();
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] depotArray = getDepotArray(subTypeList);
            String[] depotArrays = null;
            if (StringUtil.isEmpty(depotId)){
                depotArrays = getDepotArrayByDepotStatus(depotStatus);
            }else {
                depotArrays= StringUtil.isNotEmpty(depotId) ? depotId.split(",") : null;
            }
            String[] creatorArray = getCreatorArray(roleType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            String[] quotationStatusArray = StringUtil.isNotEmpty(quotationStatus) ? quotationStatus.split(",") : null;
            String[] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
            Map<String, String> accountMap = accountService.getAccountMap();
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            //TODO 要货申请单列表 depotStatus：3，配送选要货申请单 depotStatus：1
            list = synchronizationTaskMapperEx.selectAllot(typeList, subTypeList, creatorArray, statusArray, purchaseStatusArray, number, linkNumber, beginTime, endTime,
                    materialParam, organId, creator, depotId, depotArray, accountId, remark, custom3, offset, rows, payStatus, freightStatus,quotationStatusArray,custom4
                    ,color,alwaysSelect,itemType,creditStatus,depotStatus,depotArrays);
            if (null != list) {
                for (DepotHeadVo4List dh : list) {
                    if (accountMap != null && StringUtil.isNotEmpty(dh.getAccountIdList()) && StringUtil.isNotEmpty(dh.getAccountMoneyList())) {
                        String accountStr = accountService.getAccountStrByIdAndMoney(accountMap, dh.getAccountIdList(), dh.getAccountMoneyList());
                        dh.setAccountName(accountStr);
                    }
                    if (dh.getAccountIdList() != null) {
                        String accountidlistStr = dh.getAccountIdList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountIdList(accountidlistStr);
                    }
                    if (dh.getAccountMoneyList() != null) {
                        String accountmoneylistStr = dh.getAccountMoneyList().replace("[", "").replace("]", "").replaceAll("\"", "");
                        dh.setAccountMoneyList(accountmoneylistStr);
                    }
                    if (dh.getChangeAmount() != null) {
                        dh.setChangeAmount(dh.getChangeAmount().abs());
                    }
                    if (dh.getTotalPrice() != null) {
                        dh.setTotalPrice(dh.getTotalPrice().abs());
                    }
                    if (dh.getDeposit() == null) {
                        dh.setDeposit(BigDecimal.ZERO);
                    }
                    dh.setFinishDeposit(depotHeadMapperEx.getFinishDepositByNumber(dh.getNumber()));
                    if (StringUtil.isNotEmpty(dh.getSalesMan())) {
                        User user = userService.getUser(dh.getSalesMan());
                        if (null !=user){
                            dh.setSalesManStr(user.getLoginName());
                            dh.setSalesUserName(user.getUsername());
                        }
                    }
                    if (StringUtil.isNotEmpty(dh.getDepotId())) {
                        dh.setDepotName(depotService.getAnotherDepotById(dh.getDepotId()));
                    }
                    if (StringUtil.isNotEmpty(dh.getCheckDepotId())) {
                        dh.setCheckDepotName(depotService.getDepotById(dh.getCheckDepotId()));
                    }
                    if (StringUtil.isNotEmpty(dh.getAnotherDepotId())) {
                        dh.setAnotherDepotName(depotService.getAnotherDepotById(dh.getAnotherDepotId()));
                    }
                    if (dh.getOperTime() != null) {
                        dh.setOperTimeStr(getCenternTime(dh.getOperTime()));
                    }
                    if (dh.getArrivalTime() != null) {
                        dh.setArrivalTimeStr(getCenternTime(dh.getArrivalTime()));
                    }
                    dh.setMaterialsList(findMaterialsListByHeaderId(dh.getId()));
                    dh.setTotal(depotHeadMapperEx.getTotal(dh.getDefaultNumber()));
                    dh.setFinishDebt(accountItemService.getEachAmountByBillId(dh.getId()));
                    if (StringUtils.isNotEmpty(dh.getDefaultNumber())){
                        String goToType = "";
                        BigDecimal receivedQuantity = depotHeadMapperEx.getReceivedQuantity(dh.getDefaultNumber(), goToType);
                        BigDecimal outCount = depotHeadMapperEx.getSalesReturnQuantity(dh.getDefaultNumber());
                        if (receivedQuantity ==null || outCount ==null){
                            dh.setReceivedQuantity(receivedQuantity);
                        }else {
                            receivedQuantity= receivedQuantity.subtract(outCount);
                            dh.setReceivedQuantity(receivedQuantity);
                        }
                    }
                    Integer approveProcess = workflowApproveDetailMapperEx.getBillProcessByNumber(dh.getNumber());
                    if (approveProcess != null) {
                        dh.setProcess(approveProcess);
                    } else {
                        dh.setProcess(workflowProcessDetailMapperEx.getBillProcessByNumber(dh.getNumber()));
                    }
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }

    public Long countDepotHeadAllot(String type, String subType, String roleType, String status, String purchaseStatus, String number, String linkNumber,
                               String beginTime, String endTime, String materialParam, String organId, String creator, String depotId,
                               String accountId, String remark,String custom3, String payStatus, String freightStatus, String quotationStatus,
                               String custom4,String color,String alwaysSelect,String itemType,String creditStatus,String depotStatus) throws Exception {
        Long result = null;
        try {
            List<String> typeList = StringUtil.strToStringList(type);
            List<String> subTypeList = StringUtil.strToStringList(subType);
            String[] depotArray = getDepotArray(subTypeList);
            String[] depotArrays = null;
            if (StringUtil.isEmpty(depotId)){
                depotArrays = getDepotArrayByDepotStatus(depotStatus);
            }else {
                depotArrays= StringUtil.isNotEmpty(depotId) ? depotId.split(",") : null;
            }
            String[] creatorArray = getCreatorArray(roleType);
            String[] statusArray = StringUtil.isNotEmpty(status) ? status.split(",") : null;
            String[] quotationStatusArray = StringUtil.isNotEmpty(quotationStatus) ? quotationStatus.split(",") : null;
            String[] purchaseStatusArray = StringUtil.isNotEmpty(purchaseStatus) ? purchaseStatus.split(",") : null;
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            result = synchronizationTaskMapperEx.countDepotHeadAllot(typeList, subTypeList, creatorArray, statusArray, purchaseStatusArray, number, linkNumber, beginTime, endTime,
                    materialParam, organId, creator, depotId, depotArray, accountId, remark,custom3, payStatus,
                    freightStatus,quotationStatusArray,custom4,color,alwaysSelect,itemType,creditStatus,depotStatus,depotArrays);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public DepotHeadVo4List selectByHeaderId(String headerId) {
        DepotHeadVo4List depotHeadVo4List = null;
        try {
            depotHeadVo4List = depotHeadMapperEx.selectByHeaderId(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return depotHeadVo4List;
    }

    public List<String> getSalesOutByLinkNumber(String number) throws Exception {
        List<DepotHead> list = null;
        List<String> idList=null;
        DepotHeadExample example=new DepotHeadExample();
        example.createCriteria().andLinkNumberEqualTo(number).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        try {
            list = depotHeadMapper.selectByExample(example);
            if (list != null && list.size()>0){
                idList=list.stream().map(DepotHead::getId).collect(Collectors.toList());
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return idList;
    }

    public List<SalesTaxMoney> findSalesTaxMoneyList(List<String> depotList, String beginTime, String endTime,
                                                   Integer currentPage, Integer pageSize) {
        List<SalesTaxMoney> resList = new ArrayList<>();
        List<SalesTaxMoney> list = null;
        try {
            beginTime = Tools.parseDayToTime(beginTime, BusinessConstants.DAY_FIRST_TIME);
            endTime = Tools.parseDayToTime(endTime, BusinessConstants.DAY_LAST_TIME);
            list = synchronizationTaskMapperEx.findSalesTaxMoneyList(depotList,  beginTime,
                    endTime,  currentPage, pageSize);

            if (null != list) {
                for (SalesTaxMoney dh : list) {
                    dh.setNetSales(dh.getTaxLastMoney().subtract(dh.getTaxMoney()).subtract(dh.getDiscountAllPrice()));
                    resList.add(dh);
                }
            }
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }
}
